Skip to content Skip to sidebar Skip to footer

Asynctask Nullpointerexception Pressing Back Button

This is my situation. I have this AsyncTask: private class Logo extends AsyncTask { @Override protected void onPreExecute() { su

Solution 1:

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.

Solution 2:

Cancel it in onDestroy

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

Solution 3:

Instead of using AsyncTask, you may need to use IntentService

Chech this out

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

Solution 4:

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.

privateclassLogoextendsAsyncTask<Void, Void, Void> {
    private Context context;

    publicLogo(Context context) {
        this.context = context;
    }

    @OverrideprotectedvoidonPreExecute() {
        super.onPreExecute(); 
    }

    @Overrideprotected Void doInBackground(Void... params) {

        try {
            // Connect to the web siteDocumentdocument= Jsoup.connect(BLOG_URL).get();
            // Using Elements to get the class data // Locate the src attributefor(Element img : document.select("div.col-1-1 .image img[src]")) {
                StringImgSrc= img.attr("src");
                // Download image from URLInputStreamis=newjava.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");
        }
        returnnull;
    }

    @OverrideprotectedvoidonPostExecute(Void result) {

        ParsingAdapterCategorieadapter=newParsingAdapterCategorie(context, titoli, bitmap, data);
        lista.setAdapter(adapter);

    }
}

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

Logologo=newLogo(this);
    logo.execute();

Hope this solved your problem! ;-)

Best regards.

Solution 5:

This will help u..

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

}

Post a Comment for "Asynctask Nullpointerexception Pressing Back Button"