NewGuy117
NewGuy117

Reputation: 89

Stopping AsyncTask when app exits or when a new fragment is executed

I follow this RSS feed tutorial. Now when I exit the app or execute a different fragment, the app crashes. I've been cracking my head for a solution but there's still nothing. anyways, this is the code:

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

    }

Help would be very much appreciated.

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)

Upvotes: 0

Views: 90

Answers (1)

Oleksandr
Oleksandr

Reputation: 6356

It is because your fragment detached from Activity, when you trying to invoke startLisActivity method.

Add isAdded() check as first line in your startLisActivity(RSSFeed feed) method, and if fragment doesn't added just exit from method.

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

Upvotes: 1

Related Questions