Convert url to bitmap in NetworkOnMainThreadException

This question already has an answer here:

  • How do I fix android.os.NetworkOnMainThreadException? 49 answers

  • simply do as below -

    public class MyAsync extends AsyncTask<Void, Void, Bitmap>{
    
        @Override
        protected Bitmap doInBackground(Void... params) {
    
            try {
                URL url = new URL(src);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);
                return myBitmap;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
    
        }
    }
    

    Now to access the bitmap from url do as below -

    MyAsync obj = new MyAsync(){
    
            @Override
            protected void onPostExecute(Bitmap bmp) {
                super.onPostExecute(bmp);
    
                Bitmap bm = bmp;
                LinearLayout layout = new LinearLayout(getApplicationContext());
                layout.setLayoutParams(new AbsListView.LayoutParams(250, 250));
                layout.setGravity(Gravity.CENTER);
    
                ImageView imageView = new ImageView(getApplicationContext());
                imageView.setLayoutParams(new AbsListView.LayoutParams(220, 220));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setImageBitmap(bm);
    
                layout.addView(imageView);
            }
        };
    

    and then finally execute the AsynTask -

    obj.execute();
    

    You should not do any network call in your main thread like ankit said.You wrote everything in OnCreate() method.Use AsyncTask Instead.

    I would suggest you to go with volley NetworkImageView or Universal Image loader.

    to display images directly from the server.


    Try This

    URL url = new URL("http://....");
    Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
    

    Just Replace Your Url its working for me

    链接地址: http://www.djcxy.com/p/29546.html

    上一篇: 无法运行Eclipse; JVM终止。 退出代码= 13

    下一篇: 将网址转换为NetworkOnMainThreadException中的位图