2

I have an android application in which I just want to simply display text from an RSS feed in a list view. The application only retrieves the feed when I run it in debug mode, with breakpoints on certain lines in the Main activity.

I retrieve the feed asynchronously so this could be one of the reasons why this happens, but I'm not quite sure how to make it display the feed instantly when I run the app without the debugger.

Here is the main activity:

public class MainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> headlines = new ArrayList<>();
    RetrieveFeed getXML = new RetrieveFeed();

    getXML.execute();

    headlines = getXML.heads();

    // Binding data
    ArrayAdapter adapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, headlines);

    setListAdapter(adapter);

}}

Here is the class which does the background retrieval in the background:

public class RetrieveFeed extends AsyncTask {

URL url;
ArrayList<String> headlines = new ArrayList();
ArrayList<String> links = new ArrayList();


@Override
protected Object doInBackground(Object[] params) {

    try {
        //does specific stuff here :)

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return headlines;
}

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

public ArrayList<String> heads()
{
    return headlines;
}}
HaroldHibari
  • 422
  • 3
  • 12

1 Answers1

3

The problem is you're trying to access the data before your AsyncTask finishes.

getXML.execute();
headlines = getXML.heads();
// you execute your AsyncTask here and try to access it's data
// immediately, without waiting for it to finish execution

To fix this, you need to override onPostExecute() in your AsyncTask, (which is get called after doInBackground() finishes) and populate/refresh your ListView from there.

You could either make RetrieveFeed an inner class of MainActivity, so you have direct access to your ListView, or implement callback mechanism via an interface.

If you choose the latter, check out this answer for an example.

To show a ProgressDialog during execution, you should override onPreExecute() as well. Show your dialog from there and dismiss it in onPostExecute().

Check this answer for an example.

Community
  • 1
  • 1
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63