Android: Can't perform network operation on ma

2020-02-15 07:40发布

Possible Duplicate:
android.os.NetworkOnMainThreadException

I'm trying to build an RSS reader for android. Here is my code. I get error saying can't perform network operation on thread.

URL url = null;
try {
url = new URL((data.get(position).getThumbnail()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
try {
content = (InputStream)url.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(content , "src"); 
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}

Details: API is 16 I'm using XP pro , SP3. Android os: Jelly Bean

Here is my logcat error: http://pastebin.com/9wyVpNHV

标签: android
3条回答
三岁会撩人
2楼-- · 2020-02-15 08:15

Correct. As of Android 4.0 (or perhaps 4.1), you automatically fail if you perform network I/O on the main application thread. Please move your above code to a background thread, such as an AsyncTask.

查看更多
家丑人穷心不美
3楼-- · 2020-02-15 08:15

Use a thread and a handler to easily exchange data between UI thread and others threads

//Handler to send commands to UI thread
    Handler handler = new Handler();

    Thread th = new Thread(new Runnable() {
        public void run() {

            URL url = null; 
            InputStream content = null;
            try { 
                url = new URL((data.get(position).getThumbnail())); 

                content = (InputStream)url.getContent();
                Drawable d = Drawable.createFromStream(content , "src");  
                final Bitmap mIcon1 = BitmapFactory.decodeStream(url.openConnection().getInputStream());; 

                handler.post(new Runnable() {

                    public void run() {
                        //here you can do everything in UI thread, like put the icon in a imageVew
                    }
                });

            } catch (Exception e) { 
                e.printStackTrace();
                handler.post(new Runnable() {

                    public void run() {
                        Toast.makeText(YourActivityName.this, e.getMessage(), Toast.LENGTH_LONG);
                    }
                });
            } 


        }
    });
    th.start();
查看更多
Animai°情兽
4楼-- · 2020-02-15 08:22

As said, on latests APIs network operations should be done in a separate thread or they will rise an exception. Here's some examples from the developer's site:

Perform Network Operations on a Separate Thread

查看更多
登录 后发表回答