Issue
I use retrofit2 to Get some string data and image url from the server and recyclerview shows the received data.
I used a thread to get an image with url.
However, since threads are asynchronous, the problem is that the next action is taken while the image is being retrieved by url.
This is the code that I use to retrieve data using retrofit
public void getData(ArrayList<String> IdList, int len) {
Call<RepoReviewData> call = gitHubService.getReviewListData(IdList);
call.enqueue(new Callback<RepoReviewData>() {
@Override
public void onResponse(Call<RepoReviewData> call, Response<RepoReviewData> response) {
RepoReviewData repo = response.body();
String message = repo.getMessage();
if(message.equals("found")){
List<RepoReviewData.ReviewList> reviewList = repo.getReviewList();
reviewDataset.clear();
for(int i = 0; i < len; i++) {
String Id = reviewList.get(i).getUser_Id();
ArrayList<String> image_IDs = reviewList.get(i).getReview_Image_List();
task.execute(image_IDs);
}
reviewAdapter.addAll(reviewDataset);
reviewAdapter.setProgressMore(true);
reviewAdapter.setMoreLoading(true);
}
}
@Override
public void onFailure(Call<RepoReviewData> call, Throwable t) {
}
});
}
and this is my asynctask code
private class back extends AsyncTask<String[], Integer,ArrayList<Bitmap>> {
@Override
protected ArrayList<Bitmap> doInBackground(String[]... urls) {
try{
images = new ArrayList<>();
int Alen = urls.length;
for(int i = 0; i<Alen; i++){
java.net.URL myFileUrl = new URL(urls[i].toString());
HttpURLConnection conn = (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bmImg = BitmapFactory.decodeStream(is);
images.add(bmImg);
}
}catch(IOException e){
e.printStackTrace();
}
return images;
}
protected void onPostExecute(ArrayList<Bitmap> img){
}
}
But it runs asynchronously and does not work the way I want.
I know that I need to update recyclerview with the value returned after the asynctask.
But I do not know how to do it.
If you know how to do this or if you know a good example, I would appreciate it if you let me know.
Thank you for reading and hope you have a good day!
Solution
You don't need to download images and get Bitmap
using AsyncTask
You can simply use Glide or Picasso library to load images in your RecyclerView
In your onBindViewHolder
holder user below code
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String url = list.get(position).imageurl;
Glide.with(context)
.load(url)
.placeholder(R.drawable.piwo_48)
.transform(new CircleTransform(context))
.into(holder.imageView);
}
Hope this will help
Answered By - Parvinder Maan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.