AsynkTask NullPointerException异常pressing后退按钮 [英] AsynkTask nullPointerException pressing back button

查看:151
本文介绍了AsynkTask NullPointerException异常pressing后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况。我有这个asynktask

This is my situation. I have this asynktask

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);

        }
    }

如果我preSS它就像一个日志错误崩溃后退按钮:

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 null i think. What can i do?

推荐答案

基本上,你必须把onPostExecute()的code a。如果(getActivity()!= NULL)内...以prevent情况下,像旋转屏幕。

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

但是,在你开始你的AsyncTask的execute()?你必须尊重片段的生命周期......比如说,你应该把它的 Fragment.onActivityCreated() Fragment.onResume() ..不上在 Fragment.onCreate(),因为此时活性不附yet..therefore getActivity()总是会 NULL

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.

这篇关于AsynkTask NullPointerException异常pressing后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆