Hot questions for Using Glide in android volley

Top 10 Java Open Source / Glide / android volley

Question:

i have created app for receiving image from server with volley and show in recyclerview in my app with glide, my app have progressdialog and show progress when app download image from server with glide but often my app stop in progress and don't work like screenshot below

i have to close app and open it again what solution for this problem yo can see my code this below

 RecyclerView recycler_view;
 static final String url="";
 ArrayList<Image> images;
 GalleryAdapter mAdapter;
 ProgressDialog pd;
 public static Button btn_buy;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

recycler_view=(RecyclerView)findViewById(R.id.recycler_view);
btn_buy=(Button)findViewById(R.id.btn_buy);


pd=new ProgressDialog(this);
pd.setCancelable(false);

images=new ArrayList<>();
mAdapter=new GalleryAdapter(getApplicationContext(),images);


RecyclerView.LayoutManager mLayoutManager=new 
GridLayoutManager(getApplicationContext(),2);
recycler_view.setLayoutManager(mLayoutManager);

recycler_view.setAdapter(mAdapter);

ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);

recycler_view.addOnItemTouchListener(new 
GalleryAdapter.RecyclerTouchListener(getApplicationContext(),recycler_view, 
new GalleryAdapter.ClickListener() {
@Override
public void onClick(View view, int position) {

Bundle bundle=new Bundle();
bundle.putSerializable("images",images);
bundle.putInt("position",position);



FragmentTransaction ft=getFragmentManager().beginTransaction();

SlideshowDialogFragment newFragment=SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft,"slideshow");


}

@Override
public void onLongClick(View view, int position) {

}
}));

btn_buy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,IABactivity.class);
startActivity(intent);

}
});


fetchImages();
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                     String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {

// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

      // permission was granted, yay! Do the
      // contacts-related task you need to do.
    } else {

      // permission denied, boo! Disable the
      // functionality that depends on this permission.
      Toast.makeText(MainActivity.this, "دسترسی به حافظه داخلی لغو شد!!!", Toast.LENGTH_LONG).show();
    }
    return;
  }

  // other 'case' lines to check for other
  // permissions this app might request
}
}



public void fetchImages()
{

pd.setMessage("Please wait ...");
pd.show();


StringRequest req = new StringRequest(url,
  new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
      Log.d("", response.toString());
      pd.hide();

      images.clear();
      try {
        JSONObject object = new JSONObject(response);
        JSONArray dataArray = object.getJSONArray("data");

        for (int i = 0; i < dataArray.length(); i++) {
          JSONObject dataObject = dataArray.getJSONObject(i);

          Image image = new Image();
          image.setName(dataObject.getString("name_client"));

          // JSONObject url = object.getJSONObject("url");
          image.setSmall(dataObject.getString("small"));
          image.setOriginal(dataObject.getString("orginal"));
          image.setTimestamp(dataObject.getString("timestamp"));

          images.add(image);

        }
      } catch (JSONException e) {
        e.printStackTrace();
      }

      mAdapter.notifyDataSetChanged();
    }
  }, new Response.ErrorListener() {
  @Override
  public void onErrorResponse(VolleyError error) {
    Log.e("", "Error: " + error.getMessage());
    pd.hide();
  }
});


AppController.getmInstance().addToRequsetQueue(req);

}
}

Answer:

Use pd.dismiss() instead of pd.hide().

Question:

I am using Volley library in my app to upload image and Glide for setting image to textview. I have button to update image which opens gallery and let user select the image. The file is then uploaded in the specific folder successfully, but the image remains same. I also tried logout and login user which erases the values in ShredPreferences, all data updates, but image remains same. The older image is replaced by new in server folder, but still shows in app. It only updates after clearing app data from Settings. Why is this happening? does glide stores the cache data? how to get rid of this?


Answer:

Glide caches the image from server by default. So if your URL is not changing, it will show you the image from the cache. To work around this, you can use RequestOptions:

RequestOptions requestOptions = new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true);

 Glide.with(this)
      .load(YOUR_IMAGE_URL)
      .apply(requestOptions)
      .into(YOUR_IMAGEVIEW);

EDIT (Picasso)

If you are using Picasso, the same case applies. In this case you should use:

Picasso.with(this)
                .load(YOUR_IMG_URL)
                .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                .networkPolicy(NetworkPolicy.NO_CACHE)
                .into(YOUR_IMAGEVIEW);

Question:

hi guys i have a card view that populate it's data from a json. I parse json with volley and it is successfull . but in card view there is nothing to show

here is my json

{"photo":[{"id":"4","profile_id":"mahdi","caption":"hello","image_url":"https:\/\/hemispheric-suggest.000webhostapp.com\/img\/img\/birjand.jpg","profile_img_url":"https:\/\/hemispheric-suggest.000webhostapp.com\/prof\/prof\/prof_1.jpg","insert_time":"2017-07-09 11:21:44"}

and my fragment adapter :

private RecyclerView recyclerView;
private RequestQueue mRequestQueue;
ArrayList<Card> list = new ArrayList<>();

String url = "My url";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag,container,false);
    recyclerView = (RecyclerView) view.findViewById(R.id.recycler);

    mRequestQueue = Volley.newRequestQueue(getActivity());

    list();

    LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
    MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setAdapter(new Adapter(list));
    return view;
}


public class Adapter extends RecyclerView.Adapter<Adapter.MyviewHolder>{

   // private ArrayList<Card> list;

    public Adapter(ArrayList<Card> data) {
        list = data;
    }

    public class MyviewHolder extends RecyclerView.ViewHolder{

        public TextView textView;
        public ImageView imageView;
        public MyviewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.textView);
            imageView = (ImageView) itemView.findViewById(R.id.imageView);
        }
    }

    @Override
    public MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row,parent,false);
        return new MyviewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyviewHolder holder, int position) {

        Card card = list.get(position);
        holder.textView.setText(card.getName());
        Glide.with(getActivity()).load(card.getImg()).into(holder.imageView);

    }



    @Override
    public int getItemCount() {
        return list.size();
    }
}

public void list() {

    JsonObjectRequest object = new JsonObjectRequest(Request.Method.GET, url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try{

                        JSONArray array = response.getJSONArray("photo");
                        for (int i = 0; i <array.length() ; i++) {
                            JSONObject temp = array.getJSONObject(i);
                            Card card = new Card();
                            card.setName(temp.getString("profile_id"));
                            card.setImg(temp.getString("image_url"));
                            list.add(card);
                        }


                    }catch (Exception ex){
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }
    );
    mRequestQueue.add(object);
}
}

Answer:

Volley is asynchronus, so when you call:

recyclerView.setAdapter(new Adapter(list));

just a few milliseconds after you enqueued your request, It's very likely that the list is still empty because Volley hasn't received any response yet. You should set your adapter once you get the response inside the onResponse callback.

Question:

I want to show progress bar(showing percentage) using Volley/ Glide/Picasso or other network call libraries. There are a lot of solutions but not by the Volley/ Glide/Picasso, how can I get file image size before downloading and with time remaining size so that I can show with the progress bar.

Use Picasso.

Picasso.with(MainActivity.this).load(server_url).into(image_download);

using Glide

 GlideApp
.with(myFragment)
.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.into(myImageView);

Answer:

Try this using glide

progressBar = (ProgressBar)findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
        Glide.with(context)
                .load(imageUrl)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        progressBar.setVisibility(View.GONE);
                        return false;
                    }
                })
                .into(imageview);

with Picasso

Picasso.with(context)
            .load(imageUrl)
            .into(imageview, new com.squareup.picasso.Callback() {
                        @Override
                        public void onSuccess() {
                            //do something when picture is loaded successfully
                             progressBar.setVisibility(View.GONE);

                        }

                        @Override
                        public void onError() {
                            //do something when there is picture loading error
                        }
                    });

with AsyncTask

public class DownloadImage extends AsyncTask<String, Integer, Bitmap> {
    ImageView bmImage;
    ProgressBar progressBar;

    public DownloadImage(ImageView bmImage, ProgressBar progressBar) {
        this.bmImage = bmImage;
        this.progressBar = progressBar;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.d("Error", e.getStackTrace().toString());

        }
        return mIcon11;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

use like this

 new DownloadImage(imamgeview,progressBar).execute(url);