3

I want to add images from certain URLS dynamically to a linear layout.While running the piece of code i got error Unable to start activity

ComponentInfo: android.os.NetworkOnMainThreadException at com.example.star.example.CompinfoActivity.getBitmapFromURL(CompinfoActivity.java:70) at com.example.star.example.CompinfoActivity.insertPhoto(CompinfoActivity.java:50) at com.example.star.example.CompinfoActivity.onCreate(CompinfoActivity.java:38)

Please help.Here is my code for the activity below.

public class CompinfoActivity extends AppCompatActivity {

Dialog dialog;
LinearLayout myGallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compinfo);

    dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.activity_compinfopopup);
    dialog.getWindow().getAttributes().width = AbsListView.LayoutParams.MATCH_PARENT;
    dialog.getWindow().getAttributes().height = AbsListView.LayoutParams.WRAP_CONTENT;
    dialog.show();

    myGallery = (LinearLayout) dialog.findViewById(R.id.mygallery);
    myGallery.addView(insertPhoto("http://example.com/a.png"));
    myGallery.addView(insertPhoto("http://example.com/b.png"));
    myGallery.addView(insertPhoto("http://example.com/c.png"));
    myGallery.addView(insertPhoto("http://example.com/d.png"));
    new MyTask().execute();



}

View insertPhoto(String path){
    Bitmap bm;
    bm =  getBitmapFromURL(path);
    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);
    return layout;
}


public static Bitmap getBitmapFromURL(String src) {
    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;
    }
}
Jas
  • 3,207
  • 2
  • 15
  • 45
Ashish
  • 188
  • 1
  • 2
  • 11

7 Answers7

8

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();
kevz
  • 2,727
  • 14
  • 39
2

Call this method to convert Url to Bitmap in android

public static Bitmap getBitmapFromURL(String url) {
        try {
            URL url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmapFrmUrl = BitmapFactory.decodeStream(input);
            return bitmapFrmUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

Dont forget to add INTERNET Permission im AndroidManifest.xml

Sabyasachi
  • 3,499
  • 2
  • 14
  • 21
1

Try This

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

Just Replace Your Url its working for me

RushDroid
  • 1,570
  • 3
  • 21
  • 46
1

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.

Community
  • 1
  • 1
Asif Sb
  • 785
  • 9
  • 38
0

You can not make any network call on UI main thread. Implement AsyncTask like below and call

new LoadImage(imageView).execute()

Async Task Implementation::

class LoadImage extends AsyncTask<Object, Void, Bitmap>{

    private ImageView imv;
    private String path;

    public LoadImage(ImageView imv) {
         this.imv = imv;
         this.path = imv.getTag().toString();
    }

@Override
protected Bitmap doInBackground(Object... params) {
    Bitmap bitmap = null;
    File file = new File( 
            Environment.getExternalStorageDirectory().getAbsolutePath() + path);

    if(file.exists()){
        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    }

    return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
    if (!imv.getTag().toString().equals(path)) {
           /* The path is not same. This means that this
              image view is handled by some other async task. 
              We don't do anything and return. */
           return;
    }

    if(result != null && imv != null){
        imv.setVisibility(View.VISIBLE);
        imv.setImageBitmap(result);
    }
}

}

Rakesh
  • 756
  • 1
  • 9
  • 19
0

To show the pictures in the app downloading them in the storage and then showing them works

You will get your answer by searching about how to download a file, writing an OnDownloadCompleteListener

and reloading your imageView each time a pic is downloaded.

esy
  • 33
  • 3
0

Change your insertPhoto(String path) method as follow:

View insertPhoto(String path){   
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);    

  //Download and display image
        new AsyncTask<String, Void, Bitmap>(){


            @Override
            protected Bitmap doInBackground(String... urls) {
                 String url = urls[0];

                Bitmap mIcon11 = null;
                try {


                   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                   connection.setDoInput(true);
                   connection.connect();
                   InputStream input = connection.getInputStream();
                   mIcon11 = BitmapFactory.decodeStream(input);



                } catch (Exception e) {
                    Log.e("Error for image ", e.getMessage());
                    e.printStackTrace();
                    mIcon11 = null;
                }
                return mIcon11;
            }


            protected void onPostExecute(Bitmap result) {
                if(result!= null){
                    imageView.setImageBitmap(null);
                    imageView.setImageBitmap(result);                       

                }

            }
        }.execute(path);

layout.addView(imageView);
return layout;

}

Hope this helps.

techroid
  • 477
  • 4
  • 11