我使用Retrofit2从服务器获取一些字符串数据和图像URL,然后recyclerview显示接收到的数据。
我使用了一个线程来获取带有url的图像。
但是,由于线程是异步的,所以问题在于在通过url检索图像时采取了下一个动作。
这是我用于通过改造来检索数据的代码
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) {
}
});
}
这是我的异步任务代码
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){
}
}
但是它异步运行,无法按照我想要的方式工作。
我知道我需要用asynctask之后返回的值更新recyclerview。
但是我不知道该怎么做。
如果您知道该怎么做,或者您知道一个好的例子,请告诉我。
谢谢您的阅读,希望您有美好的一天!
答案 0 :(得分:1)
您无需下载图像并使用Bitmap
来获取AsyncTask
您可以简单地使用Glide或Picasso库将图像加载到RecyclerView
在您的onBindViewHolder
持有人用户下方,代码
@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);
}
希望这会有所帮助