NetworkOnMainThread错误 [英] NetworkOnMainThread Error

查看:122
本文介绍了NetworkOnMainThread错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我尝试从我的MSQL数据库产品的信息。价格和标题确实工作取得但是不是图像。我不断收到NetworkOnMainThread错误。我知道这是因为code为runOnUiThread这样的主线。但是,我尝试了所有可能的解决方案,一旦我删除runOnUIThread,只有有一个新的可运行的code内不执行,请帮助?任何解决方案是感激。

  // TODO自动生成方法存根
胎面loadingThread =新主题(){
    字符串结果=;
    @覆盖
    公共无效的run(){
        // TODO自动生成方法存根
        尝试{
            HTT presponse响应= httpClient.execute(httpPost);
            HttpEntity httpentity = response.getEntity();
            为InputStream的InputStream = httpentity.getContent();            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中,ISO-8859-1),8);
            StringBuilder的StringBuilder的=新的StringBuilder();
            串线= NULL;            而((行= reader.readLine())!= NULL){
                stringBuilder.append(行+\\ n);
            }
            inputStream.close();
            结果= stringBuilder.toString();            JSONArray阵列=新JSONArray(结果);
            的JSONObject的JSONObject = NULL;
            的JSONObject = Array.getJSONObject(0);            字符串productTitle = jsonObject.getString(标题);
            字符串productSku,则= jsonObject.getString(价格);
            最后弦乐productImage = jsonObject.getString(图片网址);            productTextViewPrice.setText(productSku,则);
            productTextViewTitle.setText(productTitle);            runOnUiThread(新的Runnable(){
                @覆盖
                公共无效的run(){
                    // TODO自动生成方法存根
                    // TODO自动生成方法存根
                    尝试{
                        InputStream为=(InputStream的)新的URL(productImage).getContent();
                        Log.i(log_URL,URL是+ productImage);
                        可绘制proImage = Drawable.createFromStream(是,SRC名);
                        productImageFull.setImageDrawable(proImage);
                    }赶上(例外五){
                        Log.i(log_Result,错误越来越像+ e.toString());
                    }
                }
            });        }赶上(例外五){        }
        super.run();
    }
};
loadingThread.start();


解决方案

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html.

NetworkOnMainThread发生,因为你可能在我的主UI线程做相关的元网络操作。你必须要在UI线程在后台线程和UPDATA UI与网络相关的操作。

您可以使用asycntask。 http://developer.android.com/reference/android/os/AsyncTask.html

 类TheTask扩展的AsyncTask<太虚,太虚,太虚>
{
      在preExecute保护无效()
      {super.on preExecute();
                //显示progressdialog。
      }       保护无效doInBackground(无效... PARAMS)
      {
            // http请求。这里不更新用户界面            返回null;
      }       保护无效onPostExecute(虚空结果)
      {
                super.onPostExecute(结果);
                //解雇progressdialog。
                //更新UI
      } }

使用异步TAKS如果网络操作为短周期。

直接从文档

AsyncTasks理论上应该用于短操作(几秒钟之最。)如果您需要保留的线程运行的对于长时间,这是非常建议您使用由java.util.concurrent的pacakge如遗嘱执行人,并ThreadPoolExecutor的提供FutureTask提供的各种API。

您可以考虑的替代的AsyncTask robospice 的https:// github上。 COM / OCTO-在线/ robospice

Hi everyone am trying to retrieve product information from my MSQL database. The price and title does work to get however not the image. I keep getting the NetworkOnMainThread error. I know this is because the code is in runOnUiThread thus the main thread. But I tried all possible solutions once I remove runOnUIThread and only have a new runnable the code inside doesn't execute please help? any solution is grateful.

// TODO Auto-generated method stub
Tread loadingThread = new Thread(){
    String result = "";
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try{
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity httpentity=response.getEntity();
            InputStream inputStream = httpentity.getContent();  

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;

            while ((line = reader.readLine())!=null){
                stringBuilder.append(line+"\n");
            }
            inputStream.close();        
            result=stringBuilder.toString();

            JSONArray Array = new JSONArray(result);
            JSONObject jsonObject=null;
            jsonObject = Array.getJSONObject(0);

            String productTitle = jsonObject.getString("title");
            String productPrice = jsonObject.getString("price");
            final String productImage = jsonObject.getString("image_url");

            productTextViewPrice.setText(productPrice);
            productTextViewTitle.setText(productTitle);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    // TODO Auto-generated method stub
                    try {
                        InputStream is = (InputStream) new URL(productImage).getContent();
                        Log.i("log_URL","URL is " + productImage);
                        Drawable proImage = Drawable.createFromStream(is, "src name");
                        productImageFull.setImageDrawable(proImage);
                    } catch (Exception e) {
                        Log.i("log_Result","error getting image " + e.toString());
                    }
                }
            });

        } catch (Exception e){

        }
        super.run();
    }
};
loadingThread.start();

解决方案

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html.

NetworkOnMainThread occurs because you might me doing netowrk related operation on the main UI Thread. You have to make network related operation in the background thread and updata ui on the ui thread.

You can use a asycntask. http://developer.android.com/reference/android/os/AsyncTask.html

class TheTask extends AsyncTask<Void,Void,Void>
{
      protected void onPreExecute()
      {           super.onPreExecute();
                //display progressdialog.
      } 

       protected void doInBackground(Void ...params)
      {  
            //http request. do not update ui here

            return null;
      } 

       protected void onPostExecute(Void result)
      {     
                super.onPostExecute(result);
                //dismiss progressdialog.
                //update ui
      } 

 }

Use async taks if the network operation is for a short period.

Straight from the doc

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

You can consider an alternative to asynctask robospice.https://github.com/octo-online/robospice.

这篇关于NetworkOnMainThread错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆