简体   繁体   中英

AsyncTask nullPointerException pressing back button

This is my situation. I have this AsyncTask:

private class Logo extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute(); 
        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
                // Connect to the web site
                Document document = Jsoup.connect(BLOG_URL).get();
                // Using Elements to get the class data 
                // Locate the src attribute
                for(Element img : document.select("div.col-1-1 .image img[src]")) {
                    String ImgSrc = img.attr("src");
                    // Download image from URL
                    InputStream is = new java.net.URL(ImgSrc).openStream();
                    //add Bitmap to an array
                    bitmap.add(BitmapFactory.decodeStream(is));
                 }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("ESEMPIO", "ERRORE NEL PARSING DELLE IMMAGINI");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            ParsingAdapterCategorie adapter = new ParsingAdapterCategorie(getActivity(), titoli, bitmap, data);
            lista.setAdapter(adapter);

        }
    }

If I press the back button it crashes with a log error like:

FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)

This is because the activity result is null, I think. What can I do?

Basically you have to put the code of the onPostExecute() inside a if(getActivity() != null)...to prevent cases like rotating screen..

BUT where do you start your AsyncTask execute()? You have to respect the lifecycle of the fragment...for instance, you should call it on the Fragment.onActivityCreated() OR Fragment.onResume() ..NOT on the Fragment.onCreate() because at this point the activity is not attached yet..therefore getActivity() will always be NULL .

Cancel it in onDestroy

@Override
public void onDestroy() {
    if (asynchtask!=null) {
        asynchtask.cancel(true);
    }
    super.onDestroy();
}

Instead of using AsyncTask , you may need to use IntentService

Chech this out

http://developer.android.com/training/run-background-service/create-service.html

The AsyncTask is running in your background while the activity is finished. So getActivity() returns null. You have to change your code as follows and pass the context in the constructor of your AsyncTask.

private class Logo extends AsyncTask<Void, Void, Void> {
    private Context context;

    public Logo(Context context) {
        this.context = context;
    }

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

    @Override
    protected Void doInBackground(Void... params) {

        try {
            // Connect to the web site
            Document document = Jsoup.connect(BLOG_URL).get();
            // Using Elements to get the class data 
            // Locate the src attribute
            for(Element img : document.select("div.col-1-1 .image img[src]")) {
                String ImgSrc = img.attr("src");
                // Download image from URL
                InputStream is = new java.net.URL(ImgSrc).openStream();
                //add Bitmap to an array
                bitmap.add(BitmapFactory.decodeStream(is));
             }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("ESEMPIO", "ERRORE NEL PARSING DELLE IMMAGINI");
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        ParsingAdapterCategorie adapter = new ParsingAdapterCategorie(context, titoli, bitmap, data);
        lista.setAdapter(adapter);

    }
}

Then you can call your AsyncTask in the Activity as follows:

    Logo logo = new Logo(this);
    logo.execute();

Hope this solved your problem! ;-)

Best regards.

This will help u..

if(null != getActivity) { //Paste ur code

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM