1

I am using endless recycler view to show multiple posts. but if my internet speed is slow and image not loaded on time when I click on imageview it crashes the app. I am sending url from activity to another through intent.

Here is the code

RecyclerAdapter.java

 holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
  String icon = jsonData.get((position)).getImg();
  Intent intent = new Intent(context, Detail.class);
  intent.putExtra("app_icon", icon);
  }
  context.startActivity(intent);

Detail.java

     detail_icon = (ImageView) findViewById(R.id.detail_icon);
    String appicon = getIntent().getStringExtra("app_icon");
      try {
            detail_icon.setImageBitmap(BitmapFactory.decodeStream((InputStream) new URL(appicon).getContent()));
    }catch (IOException e2) {
        e2.printStackTrace();
    }

Crashing on this line while image is not loaded and I click on imageview.

   detail_icon.setImageBitmap(BitmapFactory.decodeStream((InputStream) new URL(appicon).getContent()));

Logcat

        Process: com.example.lenovo.connectiontest, PID: 26525
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo.connectiontest/com.example.lenovo.connectiontest.Activity.Detail}: android.os.NetworkOnMainThreadException

   at com.example.lenovo.connectiontest.Activity.Detail.onCreate(Detail.java:233)
Shahroz javaid
  • 169
  • 1
  • 1
  • 12

2 Answers2

0

Yes its solved my problem

  Thread thread = new Thread(new Runnable() {

@Override
public void run() {
    try  {
        //Your code goes here
    } catch (Exception e) {
        e.printStackTrace();
    }
}
  });

  thread.start();
Shahroz javaid
  • 169
  • 1
  • 1
  • 12
0

Why don't you use Glide? Add this to your app level Gradle file:

 

// Glide image library

    compile 'com.github.bumptech.glide:glide:3.7.0'

And then use it in any activity with the provided URL, the image is cached and doesn't need to be downloaded again (in my case!) Then add this to your Activity:

Glide.with(this).load(urlProfileImg)

                .crossFade()

                .thumbnail(0.5f)

                .bitmapTransform(new CircleTransform(this))

                .diskCacheStrategy(DiskCacheStrategy.ALL)

                .into(imgProfile);

Or maybe try using Picasso - it has a superclass that you can override while the image is loading:

Picasso.with(context).load(url).into(target, new Callback(){ @Override public void onSuccess() { } @Override public void onError() { } });

Sorry for the bad code formatting! I hope this helps!

Sayan N.
  • 15
  • 5