Android Load Network picture report Android.os.NetworkOnMainThreadException exception

Source: Internet
Author: User

Android Load Network pictures can be broadly divided into two, low and high versions. An API with a lower version, such as 4.0 or lower, can be implemented directly using http:

1.main.xml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"android:orientation= "vertical" >     <TextViewAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "@string/imagepath" />         <EditTextAndroid:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Http://10.191.92.7:8080/web/xiaoxiao.jpg"Android:id= "@+id/imagepath"/>         <ButtonAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/button"Android:id= "@+id/button"/>              <ImageViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:id= "@+id/imageview"/>                </LinearLayout>

2.mainactivity.java

Package Ygc.yxb.image;import Ygc.yxb.service.imageservice;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.view.View; Import Android.widget.button;import Android.widget.edittext;import Android.widget.imageview;import    Android.widget.toast;public class Mainactivity extends Activity {private EditText pathtext;        Private ImageView ImageView;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        Get Picture path pathtext= (EditText) This.findviewbyid (R.id.imagepath);       Obtain the ImageView imageview= (imageView) This.findviewbyid (R.id.imageview) to be displayed;              Get button buttons button= (button) This.findviewbyid (R.id.button);            Register the button's Click event Button.setonclicklistener (New Buttonclicklistener ()); } Private Final class Buttonclicklistener implements View.onclicklistener{@Override public void OnClick (View v) {String path=pathtext.gettext (). toString (); try {//Business Logic Layer: GetImage method for ImageService class to get network picture byte[] data = Imageservice.getima                GE (path);                Generates a bitmap object with all the information in a byte array Bitmap Bitmap =bitmapfactory.decodebytearray (data, 0, data.length);                Imageview.setimagebitmap (bitmap);//Display picture} catch (Exception e) {e.printstacktrace ();            Toast.maketext (Getapplicationcontext (), R.string.error, 1). Show (); }                                }                    }}

3.imageservice.java

Package Ygc.yxb.service;import Java.io.inputstream;import Java.net.httpurlconnection;import java.net.URL;import Ygc.yxb.utils.streamtool;public class ImageService {    /**     * Get the data of the network picture     * @param path network picture paths     * @return     *    /public static byte[] GetImage (String path) throws Exception {                url url = new URL (path);        HttpURLConnection conn= (httpurlconnection) url.openconnection ();    HTTP protocol-based Connection object        conn.setconnecttimeout (5000);//5 s        conn.setrequestmethod ("GET");//Request Method        // Determine if the request was successful        if (Conn.getresponsecode () ==200) {            //define the input stream            inputstream instream = Conn.getinputstream ();            Return Streamtool.read (instream);                    }                return null;}    }

4.streamtool.java the input Stream tool class.

Package Ygc.yxb.utils;import Java.io.bytearrayoutputstream;import Java.io.inputstream;public class StreamTool {    /**     * Read data from Stream     * @param instream *     @return *     @throws Exception *    /public static byte[] Read ( InputStream instream) throws Exception {        Bytearrayoutputstream outputstream = new Bytearrayoutputstream ();        byte[] buffer = new byte[1024];        int len = 0;        If the data in the byte stream is not equal to-1, the description is always there, and then the loop reads the while        ((len=instream.read (buffer))!=-1) {            //puts the read data into memory            Outputstream.write (buffer);                    }        Instream.close ();        return Outputstream.tobytearray ();    }}

5.androidmanifest.xml Configure permissions to access the network in the manifest file.

<!--access to Internet permissions--
<uses-permission android:name= "Android.permission.INTERNET"/>

And if 4.0 or above version of the words can not directly obtain the picture, direct access to the network image will be reported android.os.NetworkOnMainThreadException exception, because more than 4.0 access to the network function can not occur in the main thread to run, And if the above access mode is changed to asynchronous operation will not appear on the 4.0 access to report the android.os.NetworkOnMainThreadException exception.

Such as:

New Thread () {
@Override
public void Run () {
The method you want to execute
Send an empty message to handler after execution is complete
Handler.sendemptymessage (0);
}
}.start ();

Defining Handler Objects
Private Handler Handler =new Handler () {
@Override
This is the way to execute handler when a message is sent out.
public void Handlemessage (Message msg) {
Super.handlemessage (msg);
Working with the UI
}
};

Android Load Network picture report Android.os.NetworkOnMainThreadException exception

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.