简体   繁体   English

AsyncTask nullPointerException按下后退按钮

[英]AsyncTask nullPointerException pressing back button

This is my situation. 这是我的情况。 I have this AsyncTask: 我有这个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.. 基本上,您必须将onPostExecute()的代码放入if(getActivity()!= null)中,以防止出现诸如旋转屏幕之类的情况。

BUT where do you start your AsyncTask execute()? 但是您从哪里开始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 . 您必须尊重片段的生命周期...例如,应在Fragment.onActivityCreated()Fragment.onResume() ..NOT在Fragment.onCreate()上调用它,因为此时活动尚未结束附加。.因此,getActivity()始终为NULL

Cancel it in onDestroy 在onDestroy中取消它

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

Instead of using AsyncTask , you may need to use IntentService 代替使用AsyncTask ,您可能需要使用IntentService

Chech this out this一下

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

The AsyncTask is running in your background while the activity is finished. 活动完成后,AsyncTask在后台运行。 So getActivity() returns null. 因此getActivity()返回null。 You have to change your code as follows and pass the context in the constructor of your AsyncTask. 您必须按照以下方式更改代码,并在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: 然后,您可以在Activity中调用AsyncTask,如下所示:

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

Hope this solved your problem! 希望这解决了您的问题! ;-) ;-)

Best regards. 最好的祝福。

This will help u.. 这对你有帮助

if(null != getActivity) { //Paste ur code if(null!= getActivity){//粘贴您的代码

} }

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

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