Trying to fix NetworkOnMainThreadException but gives Toast error

I'm trying to fix a Thread error for one of my preferred examples from java code geeks.

Here's the code:

public class JsonParsingActivity extends Activity {

        String url = "http://search.twitter.com/search.json?q=javacodegeeks";

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            new RetreiveFeedTask().execute(url);

        }
    }

The RetrieveFeedTask:

public class RetreiveFeedTask extends
        AsyncTask<String, Void, JsonParsingActivity> {

    private Exception exception;
    String url = "http://search.twitter.com/search.json?q=javacodegeeks";

    protected JsonParsingActivity doInBackground(String... urls) {
        try {

            InputStream source = retrieveStream(url);

            Gson gson = new Gson();

            Reader reader = new InputStreamReader(source);

            SearchResponse response = gson.fromJson(reader, SearchResponse.class);

            // Toast.makeText(this, response.query, Toast.LENGTH_SHORT).show();

            List<Result> results = response.results;

            for (Result result : results) {
                Toast.makeText(JsonParsingActivity.class, result.fromUser, Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(JsonParsingActivity feed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }

    private InputStream retrieveStream(String url) {

        DefaultHttpClient client = new DefaultHttpClient();

        HttpGet getRequest = new HttpGet(url);

        try {

            HttpResponse getResponse = client.execute(getRequest);
            final int statusCode = getResponse.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                Log.w(getClass().getSimpleName(), "Error " + statusCode
                        + " for URL " + url);
                return null;
            }

            HttpEntity getResponseEntity = getResponse.getEntity();
            return getResponseEntity.getContent();

        } catch (IOException e) {
            getRequest.abort();
            Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        }

        return null;

    }}

What's the best way to do that without errors? It's currently giving a Toast error (?).


You can't do UI stuff in doInBackground(). Hence, you can't display a Toast there. You need to move this to onPostExecute() or somewhere else. Possibly onProgressUpdate()

You could call publishProgress(results) and show the Toast in onProgressUpdate() or return results to onPostExecute() and display it there. You also have the option of sending the data back to an Activity method

AsyncTask