[Solved] Android.os.networkonmainthreadexception exception of Android

Load the network image in mainactivity. The code is as follows:

publicclassNetImageActivityextendsActivity{

StringimageUrl="http://content.52pk.com/files/100623/2230_102437_1_lit.jpg";
BitmapbmImg;
ImageViewimView;

@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView=(ImageView)findViewById(R.id.imageViewId);
imView.setImageBitmap(returnBitMap(imageUrl));
}

publicBitmapreturnBitMap(Stringurl){
URLmyFileUrl=null;
Bitmapbitmap=null;
try{
myFileUrl=newURL(url);
}catch(MalformedURLExceptione){
e.printStackTrace();
}
try{
HttpURLConnectionconn=(HttpURLConnection)myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStreamis=conn.getInputStream();
bitmap=BitmapFactory.decodeStream(is);
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
returnbitmap;
}
}

error is reported, and the information is as follows

Causedby:android.os.NetworkOnMainThreadException
atandroid.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
atjava.net.InetAddress.lookupHostByName(InetAddress.java:385)
atjava.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
atjava.net.InetAddress.getAllByName(InetAddress.java:214)
atcom.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
atcom.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
atcom.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
atcom.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
atcom.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
atcom.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
atcom.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
atcom.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)

android.os.networkonmainthreadexception means not to access the network in the main thread. Since Android 3.0, it has forced the program not to access the network in the main thread, so it should be placed in an independent thread

in development, in order to prevent the access network from blocking the main thread, it is generally necessary to put the access network in the independent thread or asynchronous thread asynctask

1. If you want to ignore these mandatory policy problems, you can add to oncreate() method

StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

and add @ suppresslint (“newapi”) to the method to try again, OK

2. Put network access into a separate thread: 

publicclassNetImageActivityextendsActivity{

StringimageUrl="http://content.52pk.com/files/100623/2230_102437_1_lit.jpg";
Bitmapbitmap;
ImageViewimView;

@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView=(ImageView)findViewById(R.id.imageViewId);
ThreadimageViewHander=newThread(newNetImageHandler());
imageViewHander.start();
}


classNetImageHandlerimplementsRunnable{
@Override
publicvoidrun(){
try{
URLurl=newURL(imageUrl);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStreamis=conn.getInputStream();
bitmap=BitmapFactory.decodeStream(is);
//Send a message to notify the UI component to display the image
handler.sendEmptyMessage(0);
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

Handlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
if(msg.what==0){
imView.setImageBitmap(bitmap);
}
}
};

}

3. Put network access into asynctask. The code is as follows: 2

publicclassNetImageActivityextendsActivity{

StringimageUrl="http://content.52pk.com/files/100623/2230_102437_1_lit.jpg";
ImageViewimView;

@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imView=(ImageView)findViewById(R.id.imageViewId);
loadImage();
}

privatevoidloadImage(){
newAsyncTask<String,Void,Bitmap>(){
//This method runs in a background thread, so the UI cannot be updated in this thread, which is the main thread
@Override
protectedBitmapdoInBackground(String...params){
Bitmapbitmap=null;
try{
Stringurl=params[0];
URLHttpURL=newURL(url);
HttpURLConnectionconn=(HttpURLConnection)HttpURL.openConnection();
conn.setDoInput(true);
conn.connect();
InputStreamis=conn.getInputStream();
bitmap=BitmapFactory.decodeStream(is);
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
returnbitmap;
}

//After the execution of doInBackground is completed, the onPostExecute method will be called by the UI thread.
// The results of the background calculation will be passed to the UI thread via this method and displayed to the user in the interface.
@Override
protectedvoidonPostExecute(Bitmapbitmap){
if(bitmap!=null){
imView.setImageBitmap(bitmap);
}
}
}.execute(imageUrl);
}

}

 

Similar Posts: