android – 尝试修复NetworkOnMainThreadException但是给Toast错误

我正在尝试为java代码极客中的一个首选示例修复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错误(?).

解决方法:

你不能在doInBackground()中做UI的东西.因此,您无法在那里显示Toast.您需要将其移动到onPostExecute()或其他位置.可能是onProgressUpdate()

您可以调用publishProgress(results)并在onProgressUpdate()中显示Toast或将结果返回到onPostExecute()并在那里显示它.您还可以选择将数据发送回Activity方法

AsyncTask

上一篇:java – GSON投掷“预期BEGIN_OBJECT但是BEGIN_ARRAY”?


下一篇:使用Gson反序列化Java 8 LocalDateTime