Displaying RSS Feed on a fragment [duplicate]

霸气de小男生 提交于 2021-02-08 12:01:22

问题


I've created an app with a drawer menu that opens a new fragment for each menu option. Within those fragments i'm attempting run several functions.

I've parsed an RSS feed, and want to display the information I've parsed on a ListView inside a specific fragment.

My main activity navigates to the fragment no problem but gets stuck with a Null Pointer exception.

This is where my lack of Java knowledge comes into play as i'm unsure of how to correct the issues.

public class IncidentsFragment extends Fragment {

    ListView lvData;
    ArrayList<String> titles;
    ArrayList<String> description;
    ArrayList<String> pubdate;

    public IncidentsFragment() {

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_incidents, container, false);
        titles = new ArrayList<String>();
        description = new ArrayList<String>();
        pubdate = new ArrayList<String>();
        ListView lvData = (ListView) view.findViewById(R.id.lvData);
        new ProcessInBackground().execute();

        // ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, titles );
        return view;

    }


    public InputStream getInputStream(URL url) {
        try {
            return url.openConnection().getInputStream();
        } catch (
                IOException e)

        {
            return null;
        }


    }


    public class ProcessInBackground extends AsyncTask<Integer, Void, Exception> {
        ProgressDialog progressDialog = new ProgressDialog(getContext());
        Exception exception = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog.setMessage("Loading RSS Feed...");
            progressDialog.show();
        }

        @Override
        protected Exception doInBackground(Integer... integers) {

            try {

                URL url = new URL("https://trafficscotland.org/rss/feeds/currentincidents.aspx");
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                // creates new instance of pull parser factory that allows XML retrieval
                factory.setNamespaceAware(false);
                // parser produced does not support XML namespaces
                XmlPullParser xpp = factory.newPullParser();
                //new instance of parser, extracts xml document data
                xpp.setInput(getInputStream(url), "UTF_8");
                //encoding is in UTF8
                boolean insideItem = false;
                int eventType = xpp.getEventType();
                //when we start reading, it returns the type of current event i.e. tag type

                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {
                        if (xpp.getName().equalsIgnoreCase("item")) {
                            insideItem = true;
                        } else if (xpp.getName().equalsIgnoreCase("title")) {
                            if (insideItem) {
                                titles.add(xpp.nextText());
                            }
                        } else if (xpp.getName().equalsIgnoreCase("description")) {
                            if (insideItem) {
                                description.add(xpp.nextText());
                            }
                        } else if (xpp.getName().equalsIgnoreCase("pubDate")) {
                            if (insideItem) {
                                pubdate.add(xpp.nextText());
                            }
                        }
                    } else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
                        insideItem = false;
                    }

                    eventType = xpp.next();
                }

            } catch (MalformedURLException e) {
                exception = e;
            } catch (XmlPullParserException e) {
                exception = e;
            } catch (IOException e) {
                exception = e;
            }


            return exception;
        }

        @Override
        protected void onPostExecute(Exception s) {
            super.onPostExecute(s);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, titles);
            lvData.setAdapter(adapter);
            //connects to data to the list view
            progressDialog.dismiss();
        }
    }


}

I've declared the listview and a few arrays at the top that will store the individual RSS tags, i've then used an Async task to perform my RSS parse.

This is the logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: gcumwd.trafficscotlandapp, PID: 13433
                                                                               java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                                   at gcumwd.trafficscotlandapp.IncidentsFragment$ProcessInBackground.onPostExecute(IncidentsFragment.java:153)
                                                                                   at gcumwd.trafficscotlandapp.IncidentsFragment$ProcessInBackground.onPostExecute(IncidentsFragment.java:83)
                                                                                   at android.os.AsyncTask.finish(AsyncTask.java:667)
                                                                                   at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Any help is greatly appreciated. All i'm trying to do is parse the RSS feed and display the data onto the ListView inside a fragment.


回答1:


The problem is that you have declared your list view in the fragment and inside onCreateView you declare it again. Your onCreateView code should look like this:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_incidents, container, false);
    titles = new ArrayList<String>();
    description = new ArrayList<String>();
    pubdate = new ArrayList<String>();
    lvData = (ListView) view.findViewById(R.id.lvData);
    new ProcessInBackground().execute();

    // ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, titles );
    return view;

}


来源:https://stackoverflow.com/questions/49430013/displaying-rss-feed-on-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!