Search code examples
androidandroid-activityandroid-intentandroid-asynctaskreload

AsyncTask reloading after changing Activity


I have a strange issue with AsyncTask. I'm using an AsyncTask to load data from my website and create a ListView with theses datas. I set a listener to each item, when i click on an item i start a new activity.

But when my new activity is loaded, the old asynctask (from the first activity) reload and makes my application crash. (Because it tries to modify a ListView which don't exist anymore)

I tested the status of my AsyncTask and it never finish (always returning RUNNING but onPostExecute() is done)

package com.wglxy.example.dash1;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter;


public class F1Activity extends DashboardActivity {


@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView (R.layout.activity_f2);
    setTitleFromActivityLabel (R.id.title_text);

    // Je démarre l'AsyncTask qui charge les interventions
    getInterventionListing Listing = new getInterventionListing();
    Listing.execute();      
}


private class getInterventionListing extends AsyncTask<Integer, Integer, ArrayList<HashMap<String, String>>>
{
    private ProgressDialog dialog;


    @Override
    protected void onPreExecute()
    {
        // Dialog qui s'affiche durant l'AsyncTask
        dialog = ProgressDialog.show(F1Activity.this, "Chargement", "Chargement des données",true,true,new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
                cancel(true);
            }});
    }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(Integer... params) 
    {
        InputStream is = null;
        String result = "";
        String problemes = "";
        String prenom = "";
        String strURL = "http://monsiteweb.com/fichier.php";
        ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();


        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("listing_intervention",""));

        // Requête HTTP
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection " + e.toString());
        }


        HashMap<String, String> map;


        // Convertion de la requête en string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        // Parse des données JSON
        try{
            JSONArray jArray = new JSONArray(result);

            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                if (json_data.getString("problemes") != "null")
                    problemes = json_data.getString("problemes");
                if (json_data.getString("prenom") != "null")
                    prenom = json_data.getString("prenom");

                map = new HashMap<String, String>();
                map.put("titre", "N°" + json_data.getInt("id_intervention") + " : " + json_data.getString("nom") + " " + prenom);
                map.put("description", problemes);
                map.put("id_intervention", json_data.getString("id_intervention"));
                map.put("id_client", json_data.getString("id_client"));
                if (json_data.getInt("statut") == 0) 
                {
                    map.put("img", String.valueOf(R.drawable.onwork));
                }
                else if (json_data.getInt("statut") == 2) 
                {
                    map.put("img", String.valueOf(R.drawable.onwait));
                }
                else if (json_data.getInt("statut") == 6) 
                {
                    map.put("img", String.valueOf(R.drawable.home));
                }
                else
                {
                    map.put("img", String.valueOf(R.drawable.other));
                }

                    listItem.add(map);

            }

        }catch(JSONException e){
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return listItem;

    }


    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> listItem)
    {
        ListView maListViewPerso = (ListView) findViewById(R.id.listviewperso);
        SimpleAdapter mSchedule = new SimpleAdapter (F1Activity.this, listItem, R.layout.listview,
                new String[] {"img", "titre", "description"}, new int[] {R.id.img, R.id.titre, R.id.description});
        maListViewPerso.setAdapter(mSchedule);


        maListViewPerso.setOnItemClickListener(new OnItemClickListener() {              
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                ListView maListViewPerso = (ListView) findViewById(R.id.listviewperso);
                HashMap<String, String> items_loaded = (HashMap<String, String>) maListViewPerso.getItemAtPosition(position);
                Intent defineIntent = new Intent(F1Activity.this, Details_intervention.class);
                Bundle objetbundle = new Bundle();
                objetbundle .putString("id_intervention",items_loaded.get("id_intervention").toString());
                objetbundle .putString("id_client",items_loaded.get("id_client").toString());
                defineIntent.putExtras(objetbundle );
                F1Activity.this.startActivity(defineIntent);
            }
        });

        dialog.dismiss();
    }



}

}

-

03-03 16:58:27.300: W/dalvikvm(656): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
03-03 16:58:27.320: E/AndroidRuntime(656): FATAL EXCEPTION: main
03-03 16:58:27.320: E/AndroidRuntime(656): java.lang.NullPointerException
03-03 16:58:27.320: E/AndroidRuntime(656):  at com.wglxy.example.dash1.F1Activity$getInterventionListing.onPostExecute(F1Activity.java:164)
03-03 16:58:27.320: E/AndroidRuntime(656):  at com.wglxy.example.dash1.F1Activity$getInterventionListing.onPostExecute(F1Activity.java:1)
03-03 16:58:27.320: E/AndroidRuntime(656):  at android.os.AsyncTask.finish(AsyncTask.java:602)

Solution

  • If you still need assistance...

    Can you post the code for the Activity you are calling through onClick -- Details_intervention.class ?

    A couple notes:

    1. You can start the activity by just having startActivity(defineIntent), you dont need F1Activity.this.

    2. Not to be picky, but you are breaking some java coding conventions throughout. Although it wont hurt the app, some things are not standard and just weird at first glance: An example is private class getInterventionListing - Classes should start with a capital letter and the preface "get" and "set" are used for methods only. So private class DownloadInterventionListing would be better.