当前位置: 首页 > 面试题库 >

试图修复NetworkOnMainThreadException但给出Toast错误

缑桐
2023-03-14
问题内容

我正在尝试从Java代码怪胎中为我的首选示例之一修复线程错误。

这是代码:

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错误(?)。


问题答案:

您无法在中做任何UI事情doInBackground()。因此,您不能在Toast那里显示一个。您需要将此移动到onPostExecute()其他地方。可能onProgressUpdate()

你可以调用publishProgress(results),并显示ToastonProgressUpdate()return resultsonPostExecute()并显示它。您还可以选择将数据发送回Activity方法

异步任务



 类似资料: