Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

android - NetworkOnMainThread Error

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+"
");
            }
            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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...