尝试修复NetworkOnMainThreadException但给出Toast错误

时间:2013-05-26 15:54:41

标签: android json gson

我正在尝试为java code geeks中的一个首选示例修复Thread错误。

以下是代码:

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

        }
    }

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;

    }}

没有错误的最佳方法是什么? 它目前正在发出Toast错误(?)。

1 个答案:

答案 0 :(得分:7)

您无法在UI中执行doInBackground()项内容。因此,您无法在那里显示Toast。您需要将其移至onPostExecute()或其他位置。可能是onProgressUpdate()

您可以致电publishProgress(results)并在ToastonProgressUpdate()return results中显示onPostExecute()并在那里显示。您还可以选择将数据发送回Activity方法

AsyncTask