当app退出或执行新片段时停止AsyncTask

时间:2015-09-23 14:38:01

标签: android android-fragments android-asynctask rss

我关注this RSS feed tutorial。现在当我退出应用程序或执行不同的片段时,应用程序崩溃了。我一直在寻找解决方案,但仍然没有。无论如何,这是代码:

public class Second_frag extends TemplateFragment {

    String RSSFEEDURL = "http://feeds.feedburner.com/TwitterRssFeedXML?format=xml";
    RSSFeed feed;
    String fileName;

    View myView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
     {
        myView = inflater.inflate(R.layout.splash,container,false);
         getActivity().setRequestedOrientation(
                 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);


        fileName = "TDRSSFeed.td";

        File feedFile = getActivity().getBaseContext().getFileStreamPath(fileName);

        ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() == null) {

            // No connectivity. Check if feed File exists
            if (!feedFile.exists()) {

                // No connectivity & Feed file doesn't exist: Show alert to exit
                // & check for connectivity
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage(
                        "Unable to reach server, \nPlease check your connectivity.")
                        .setTitle("TD RSS Reader")
                        .setCancelable(false)
                        .setPositiveButton("Exit",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        getActivity().finish();
                                    }
                                });

                AlertDialog alert = builder.create();
                alert.show();
            } else {

                // No connectivty and file exists: Read feed from the File
                Toast.makeText(Second_frag.this.getActivity(), "No connectivity. Reading last update", Toast.LENGTH_LONG).show();
                feed = ReadFeed(fileName);
                startLisActivity(feed);
            }

        } else {

            // Connected - Start parsing
            new AsyncLoadXMLFeed().execute();

        }
        return myView;


    }

    private void startLisActivity(RSSFeed feed) {

            Bundle bundle = new Bundle();

            bundle.putSerializable("feed", feed);

            List_Activity fragment = new List_Activity();

            fragment.setArguments(bundle);

            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();

                FragmentTransaction transaction = fragmentManager.beginTransaction();

                transaction.replace(R.id.workdarnit, fragment).commit();

        }


    private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {

        @Override

        protected Void doInBackground(Void... params) {

            // Obtain feed
            DOMParser myParser = new DOMParser();
            feed = myParser.parseXml(RSSFEEDURL);
            if (feed != null && feed.getItemCount() > 0)
                WriteFeed(feed);

            return null;

        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

                startLisActivity(feed);

        }

    }

    // Method to write the feed to the File
    private void WriteFeed(RSSFeed data) {

        FileOutputStream fOut =null ;
        ObjectOutputStream osw = null;

        try {
            fOut = getActivity().openFileOutput(fileName, Context.MODE_PRIVATE);
            osw = new ObjectOutputStream(fOut);
            osw.writeObject(data);
            osw.flush();
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            try {
                if(fOut !=null){
                    fOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // Method to read the feed from the File
    private RSSFeed ReadFeed(String fName) {

        FileInputStream fIn = null;
        ObjectInputStream isr = null;

        RSSFeed _feed = null;
        File feedFile = getActivity().getBaseContext().getFileStreamPath(fileName);
        if (!feedFile.exists())
            return null;

        try {
            fIn = getActivity().openFileInput(fName);
            isr = new ObjectInputStream(fIn);

            _feed = (RSSFeed) isr.readObject();
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            try {
                if(fIn !=null){
                    fIn.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return _feed;

    }




    @Override
    public final boolean enableOnBackPressed() {

        return true;
    }

    }

非常感谢帮助。

logcat的:

 java.lang.NullPointerException
            at com.example.samsung.drawer.Second_frag.startLisActivity(Second_frag.java:111)
            at com.example.samsung.drawer.Second_frag.access$200(Second_frag.java:37)
            at com.example.samsung.drawer.Second_frag$AsyncLoadXMLFeed.onPostExecute(Second_frag.java:144)
            at com.example.samsung.drawer.Second_frag$AsyncLoadXMLFeed.onPostExecute(Second_frag.java:124)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:149)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

这是因为当您尝试调用startLisActivity方法时,您的片段与Activity分离。

isAdded()方法中添加startLisActivity(RSSFeed feed)检查作为第一行,如果没有添加片段则只退出方法。

private void startLisActivity(RSSFeed feed) {
    if (!isAdded()) {
        return;
    }
    // your code
}