简体   繁体   English

第一次运行失败,第二次在Asynctask中起作用

[英]First run fails, the second works in Asynctask

I have a problem with the asynctask. 我的asynctask有问题。 When start the app shows me the error: 启动应用程序时会显示以下错误:

The process... has stopped unexpectedly.Please try again . The process... has stopped unexpectedly.Please try again 。请重The process... has stopped unexpectedly.Please try again

Then come back to start the app and it works correctly. 然后返回以启动该应用程序,它可以正常运行。 Why does this occur? 为什么会发生这种情况?

My asynctask: 我的asynctask:

private class DownloadList extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
protected void onPostExecute(Void args) {
    CustomList adapter = new CustomList(MainActivity.this, profesion,dia, imageId);
    list=(ListView)findViewById(R.id.lista);
    list.setAdapter(adapter);
}
}

CustomList.java CustomList.java

public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] profesion;
private final Integer[] imageId;
private final String[] dia;

public CustomList(Activity context,
String[] profesion, String[] dia, Integer[] imageId) {
super(context, R.layout.list_single, profesion);
this.context = context;
this.dia = dia;
this.profesion = profesion;
this.imageId = imageId;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.nombre);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
TextView txtdia = (TextView) rowView.findViewById(R.id.direccion);

txtTitle.setText(profesion[position]);
imageView.setImageResource(imageId[position]);
txtdia.setText(dia[position]);

rowView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {    

        final Dialog dialog = new Dialog(context);
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        dialog.setContentView(R.layout.dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        String nombre = profesion[position];
        ImageView img  = (ImageView)dialog.findViewById(R.id.pasar);
        TextView txth  = (TextView)dialog.findViewById(R.id.brevehistoria);
        TextView txtn = (TextView)dialog.findViewById(R.id.nombre);
        TextView txtd = (TextView)dialog.findViewById(R.id.dia);
        Button close = (Button)dialog.findViewById(R.id.close);
        TextView entrada = (TextView)dialog.findViewById(R.id.entrada);
        TextView salida = (TextView)dialog.findViewById(R.id.salida);

        if(nombre.equals("La borriquita")){ /*19 recorrido*/
            img.setImageResource(R.drawable.image_1);   
            txtn.setText("La borriquita");
            txth.setText("La cofradía remonta sus orígenes a principios de la década de los 60. Su primera salida procesional se produjo en Marzo de 1964. Desde entonces siempre ha estado ligada al Colegio Salesiano. En el año 2007 es nombrada por el Palacio Arzobispal como Hermandad de Penitencia de la Archidiócesis de Sevilla. Actualmente, El capataz es Manuel Martín Nieto y cuenta con 29 costaleros y 100 nazarenos, con túnica blanca, botonadura y cíngulo rojo y antifaz blanco o turbante del mismo color para los más pequeños.");
            txtd.setText("Domingo Ramos (Mañana)");
            entrada.setText("15:40");
            salida.setText("11:00");

        }else if(nombre.equals("El cautivo")){ /*18 recorrido */
            img.setImageResource(R.drawable.image2);
            txtn.setText("El cautivo");
            txth.setText("La cofradía fue fundada en San Miguel en 1944, cuando realizó su Estación de Penitencia por primera vez. Actualmente, Antonio Rodríguez es el capataz del paso de Cristo, con 25 costaleros. Manuel Martín Nieto en el paso de Virgen con 30 costaleros y cuenta con 261 nazarenos, con túnica blanca con capa y antifaz del mismo color.");
            txtd.setText("Domingo Ramos (Tarde)");
            entrada.setText("00:00");
            salida.setText("18:00");

        }else if(nombre.equals("La merced")){ /*21*/
            img.setImageResource(R.drawable.image5);
            txtn.setText("La merced");
            txth.setText("Primer período entre 1958-1978 y recuperada en 1987. Los capataces del Misterio del Calvario son Francisco Manuel Morilla y Juan Antonio Gil, y el paso calza 38 costaleros. El capataz de la Virgen es Manuel Martín Nieto y el paso lleva 30 costaleros y 300 nazarenos, con túnica blanca, capa y antifaz morados, botonadura y cíngulo del mismo color.");
            txtd.setText("Lunes Santo");
            entrada.setText("00:25");
            salida.setText("18:50");

        }else if(nombre.equals("Los salescianos")){/*21*/
            img.setImageResource(R.drawable.image6);
            txtn.setText("Los salescianos");
            txth.setText("La cofradía fue constituida en el año 1944. Paso de Cristo, el capataz es Luis Mejías Pérez y posee 40 hermanos. El paso de Virgen, cuyo capataz es Juan Manuel Gallardo posee 30 costaleros.");
            txtd.setText("Martes Santo");
            entrada.setText("01:30");
            salida.setText("20:00");

        }else if(nombre.equals("San francisco")){/*21*/
            img.setImageResource(R.drawable.image7);
            txtn.setText("San francisco");
            txth.setText("Fundada a finales del año 1961 en San Francisco. El capataz del paso de Cristo es Damián López y el paso calza 28 costaleros. El capataz del paso de Virgen es Antonio Miguel Lara y el mismo lleva 30 costaleros y 330 nazarenos, con túnica blanca, antifaz de color azul imperial, botonadura azul y cíngulo de esparto.");
            txtd.setText("Miércoles Santo");
            entrada.setText("01:30");
            salida.setText("19:00");

        }else if(nombre.equals("La compañía")){/*18*/
            img.setImageResource(R.drawable.image3);
            txtn.setText("La compañía");
            txth.setText("La primera noticia de la Hermandad de Gloria es de 1814. La cofradía data de 1920. Paso de Cristo, el capataz es Juan Piña y posee 29 costaleros. El paso de Virgen, cuyo capataz es Juan Antonio Gil posee 30 costaleros.");
            txtd.setText("Jueves Santo");
            entrada.setText("02:00");
            salida.setText("20:00");

        }else if(nombre.equals("Jesús")){/*21*/
            img.setImageResource(R.drawable.image4);
            txtn.setText("Jesús");
            txth.setText("La tradición popular remonta su fundación a 1609. Paso de Cristo, los capataces son D. José Coto López y D. Moisés Vázquez Martínez, y el paso tiene 35 costaleros. En el paso de Virgen, los capataces son D. Miguel Ángel Ortega Carmona y D. Antonio Palma Ramírez con 35 costaleros y 620 nazarenos, con túnica de color morado, capa rizada y botonadura del mismo color y cíngulo de esparto.");
            txtd.setText("Viernes Santo");
            entrada.setText("13:00");
            salida.setText("05:00");

        }else if(nombre.equals("Santo entierro")){/*16*/
            img.setImageResource(R.drawable.image8);
            txtn.setText("Santo entierro");
            txth.setText("La primera noticia que se tiene es del año 1541. Ha sufrido numerosos altibajos a lo largo de su historia y fue recuperada definitivamente en el año 1984. El paso de Virgen tiene 24 costaleros y su capataz es José Pérez Arias. El paso de Cristo tiene 20 costaleros y su capataz es Miguel Ortega. Actualmente, cuenta con 50 nazarenos, con túnica, capa y antifaz de color negro con cordones y cíngulo de esparto.");
            txtd.setText("Viernes Santo");
            entrada.setText("00:00");
            salida.setText("20:30");

        }else if(nombre.equals("La soledad")){/*15*/
            img.setImageResource(R.drawable.image9);
            txtn.setText("La soledad");
            txth.setText("Los orígenes de su configuración como cofradía se encuentran en el segundo tercio del siglo XIX. Deja de procesionar en 1965 y se recupera definitivamente en el año 1997. Capataz, José Manuel Morillo Sánchez al mando de 30 costaleros. Actualmente, cuenta con 120 nazarenos, con túnicas blancas, antifaz de raso negro y escapulario de los Sagrados Corazones de Jesús.");
            txtd.setText("Sábado Santo");
            entrada.setText("22:00");
            salida.setText("18:00");

        }
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
});
return rowView;
}
}

Logcat: Logcat:

03-07 12:27:44.459: E/AndroidRuntime(3191): FATAL EXCEPTION: main
03-07 12:27:44.459: E/AndroidRuntime(3191): java.lang.NullPointerException
03-07 12:27:44.459: E/AndroidRuntime(3191):     at com.semanasanta.moron.MainActivity$DownloadList.onPostExecute(MainActivity.java:517)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at com.semanasanta.moron.MainActivity$DownloadList.onPostExecute(MainActivity.java:1)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at android.os.AsyncTask.finish(AsyncTask.java:417)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at android.os.Looper.loop(Looper.java:123)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at java.lang.reflect.Method.invoke(Method.java:507)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-07 12:27:44.459: E/AndroidRuntime(3191):     at dalvik.system.NativeStart.main(Native Method)

EDIT 编辑

MainActivity.java MainActivity.java

public class MainActivity extends FragmentActivity{


Context ctx;
    /*ADs*/
    private AdView adView;
    ListView list;
    private static final String AD_UNIT_ID = "";
    ViewPager vp;
    private vpAdapter myAdapter;
    private String tabtitles[] = new String[] { "Principal", "Tiempo", "Últimas noticias" };
    final static String ScreenName = "ssmoron";
    final static String LOG_TAG = "rnc";
    ProgressDialog progressDialog;

    private ResideMenu resideMenu;
    private MainActivity mContext;
    private ResideMenuItem inicio;
    private ResideMenuItem ayudanos;
    private ResideMenuItem fuentes;
    private ResideMenuItem contacto;

    String[] profesion = {
            "La borriquita",
            "El cautivo",
            "La merced",
            "Los salescianos",
            "San francisco",
            "La compañía",
            "Jesús",
            "Santo entierro",
            "La soledad"
    };

    String[] dia = {
            "Domingo de ramos",
            "Domingo de Ramos",
            "Lunes Santo",
            "Martes Santo",
            "Miércoles Santo",
            "Jueves Santo",
            "Viernes Santo",
            "Viernes Santo",
            "Sábado Santo"
    };
    Integer[] imageId = {
            R.drawable.image_1,
            R.drawable.image2,
            R.drawable.image5,
            R.drawable.image6,
            R.drawable.image7,
            R.drawable.image3,
            R.drawable.image4,
            R.drawable.image8,
            R.drawable.image9
    };

List<HashMap<String, Object>> post_lists = new ArrayList<HashMap<String, Object>>();
    List<String> lists = new ArrayList<String>();
    ArrayAdapter<String> adapter = null;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //AppData.activity = this;
        setContentView(R.layout.activity_main);     

        ctx = this;
        //mContext = this;
        setUpMenu();
        // Create an ad.
        adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId(AD_UNIT_ID);

        /*RelativeLayout ads = (RelativeLayout) findViewById(R.id.ads);
        ads.addView(adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);*/

        /***************************************************************************/

        vp = (ViewPager) findViewById(R.id.pager);
        myAdapter = new vpAdapter();
        vp.setAdapter(myAdapter);

        DownloadList newTask = new DownloadList();
        newTask.execute();


        PagerTabStrip strip = (PagerTabStrip)findViewById(R.id.pagertabstrip);
        strip.setTabIndicatorColor(0x4e5054);
        strip.setDrawFullUnderline(true);       
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

                @Override
                public void onPageSelected(int i) {

                    switch (i) {
                    case 0:
                        break;
                    default:
                        break;
                case 1:
                    list = (ListView) findViewById(R.id.listaaa);
                    if(list.getCount() == 0){
                        startweather();
                    }else{
                    }
                    break;
                case 2:
                    list = (ListView)findViewById(R.id.listaa);
                    if(list.getCount() == 0){
                        downloadTweets();
                    }else{
                    }

                    break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }

        });
    };

    /* SLIDE */
    private class vpAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((LinearLayout)object);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //  ((ViewPager)container).removeView((LinearLayout)object);
        }

        @Override
        public void finishUpdate(ViewGroup container) {

        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            LayoutInflater inflater = (LayoutInflater)container.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = null;

            switch (position) {
            case 0:
                v = inflater.inflate(R.layout.fragmenttab1, null);
                break;
            case 1:
                v = inflater.inflate(R.layout.fragmenttab2, null);
                break;
            case 2:
                v = inflater.inflate(R.layout.fragmenttab3, null);
                break;
            }
            ((ViewPager)container).addView(v,0);
            return v;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabtitles[position];
        }

        @Override
        public Parcelable saveState() {
            return null;
        }
    }

Activity_main.xml Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#fff" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:gravity="center_vertical"
            android:paddingLeft="30dp"
            android:text="Menú"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#888888" />

        <TextView
            android:id="@+id/openmenu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:background="@drawable/ic_action_overflow"
            android:clickable="true"
            android:contentDescription="Desc"
            android:visibility="visible" />

        <TextView
            android:id="@+id/share"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@drawable/ic_action_share"
            android:clickable="true"
            android:contentDescription="Desc"
            android:visibility="visible" />

    </RelativeLayout>

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >

        <android.support.v4.view.PagerTabStrip
            android:id="@+id/pagertabstrip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#8D74C0"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"
            android:textColor="#fff" />
    </android.support.v4.view.ViewPager>

   <!-- <RelativeLayout
        android:id="@+id/ads"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:gravity="bottom" >
    </RelativeLayout>-->

</LinearLayout>

FragmentTab1.xml FragmentTab1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/lista"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:drawSelectorOnTop="false"
        android:fadingEdge="none" /> <!-- HEIGHT -->

    <LinearLayout
        android:id="@+id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical|center_horizontal"
            android:layout_marginTop="20dp"
            android:src="@drawable/ic_launcher" /> <!-- @drawable/emptydata -->

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="30dp"
            android:gravity="center"
            android:text="No se encontró ninguna información"
            android:textColor="#aaa"
            android:textSize="20sp" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="30dp"
            android:gravity="center"
            android:text="Inténtalo de nuevo más tarde"
            android:textColor="#aaa"
            android:textSize="20sp" />
    </LinearLayout>

</LinearLayout>
the line 517 is list.setAdapter(adapter);

This means list is null which indicates that the initialization fails 这意味着list为null,表示初始化失败

list=(ListView)findViewById(R.id.lista);

Check your MainActivit layout xml if you have a ListView with is lista . 如果您的ListView具有is lista请检查MainActivit布局xml。

If not you need to have a listview with the id lista in your layout xml. 如果不是,则需要在布局xml中具有ID为lista的listview。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 但是第一个Asynctask有效,按下按钮后第二个无效 - First Asynctask works however, Second doesn't when button pressed AsyncTask 在第一次尝试时不会在 onPostExecute 上返回 JSON 响应,但从第二次尝试开始工作正常 - AsyncTask does not return a JSON response on onPostExecute in the first try, but works fine starting from second try Asynctask在Fragment的第一次运行中不起作用 - Asynctask not working in the first run in Fragment 使用两个asynctask并用第二个活动替换第一个 - use two asynctask and replace the first with the second activity 如果第一个失败,如何并行运行任务并等待第二个,否则回复并让第二个运行 - How to run task parallel and wait for second if first Fails ,otherwise reply back and let the second one running aSyncTask死锁第二个aSyncTask - aSyncTask Deadlocking Second aSyncTask ViewPager,ListView和AsyncTask,第一页为空白,第二页中的所有数据 - ViewPager, ListView, and AsyncTask, first page blank, all data in the second page 每隔X秒运行AsyncTask以更新GPS位置 - Run AsyncTask every X second to update GPS position 使用AlarmManager在AsyncTask中下载失败时如何运行重试 - How to run a retry when download fails in AsyncTask using AlarmManager 模拟第一次调用失败,第二次调用成功 - Simulate first call fails, second call succeeds
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM