使用Retrofit和Glide下载图像。

huangapple go评论79阅读模式
英文:

Download an image using Retrofit and Glide

问题

// MainActivity:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    MyRecycleAdapter recyclerAdapter;
    List<Pictures> imageList;

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

        imageList = new ArrayList<>();

        //Create RecycleView object and pin view
        RecyclerView recycleView = findViewById(R.id.linear_layout_with_recycleView_ID);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 2);

        //Setup Adapter
        recycleView.setLayoutManager(linearLayoutManager);
        recyclerAdapter = new MyRecycleAdapter(MainActivity.this, imageList);
        recycleView.setAdapter(recyclerAdapter);

        Log.d(TAG, "onCreate: ------>called<-----");
        
        //Creating reference for MyService and receiving deserialized data.
        ApiService apiClient = ApiClient.getClient().create(ApiService.class);
        Call<List<Pictures>> call = apiClient.getFile();

        call.enqueue(new Callback<List<Pictures>>() {
            @Override
            public void onResponse(Call<List<Pictures>> call, Response<List<Pictures>> response) {
                imageList = response.body();
                Log.d(TAG, "onResponse: ------>called<-----");
                recyclerAdapter.setMyRecycleAdapter(imageList);
            }

            @Override
            public void onFailure(Call<List<Pictures>> call, Throwable t) {
                Log.d("TAG", "onFailure = ------>called<----- " + t.toString());
            }
        });

    }
}
英文:

I want to display images from https://picsum.photos/ into the imageView using recyclerView. Note that "https://picsum.photos/200" gets you a random square (200x200) image. I'm not sure if I'm using Glide and retrofit correctly (for arraylist with links it worked perfectly). I apriciate any hints. Thanks!
Edit: link to repo with all code: https://github.com/LightingTT/RecycleViewPictures

This is my ApiService:

public interface ApiService {
@GET(&quot;200/&quot;)
Call&lt;List&lt;Pictures&gt;&gt; getFile();

</code>

ApiClient:

public class ApiClient {
public static String BASE_URL = &quot;https://picsum.photos/&quot;;
private static Retrofit retrofit;
public static Retrofit getClient(){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}

Object class:

public class Pictures {
@SerializedName(&quot;picture&quot;)
private String picturesUrl;
public Pictures (String picturesUrl)
{
this.picturesUrl = picturesUrl;
}
public String getImageUrl() {
return picturesUrl;
}

Adapter:

public class MyRecycleAdapter extends RecyclerView.Adapter&lt;MyRecycleAdapter.ViewHolderClass&gt; {
private static final String TAG = &quot;MainActivity&quot;;
private Context context;
private List&lt;Pictures&gt; imageList;
//Constructor
public MyRecycleAdapter(Context context, List&lt;Pictures&gt; imageList)
{
this.context = context;
this.imageList = imageList;
}
//
public void setMyRecycleAdapter(List&lt;Pictures&gt; imageList)
{
this.imageList = imageList;
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolderClass onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_picture_view, parent, false);
ViewHolderClass linearViewHolderClass = new ViewHolderClass(view);
return linearViewHolderClass;
}
@Override
public void onBindViewHolder(@NonNull ViewHolderClass holder, int position) {
Glide
.with(context)
.load(imageList.get(position).getImageUrl())
.into(holder.imageView);
Log.d(TAG, &quot;onBindViewHolder: ------&gt;called&lt;-----&quot;);
}
@Override
public int getItemCount() {
return imageList.size();
}
public class ViewHolderClass extends RecyclerView.ViewHolder{
private ImageView imageView;
//Constructor
public ViewHolderClass(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.single_picture_id);
}
}

And MainActivity:

public class MainActivity extends AppCompatActivity {
private static final String TAG = &quot;MainActivity&quot;;
MyRecycleAdapter recyclerAdapter;
List&lt;Pictures&gt; imageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageList = new ArrayList&lt;&gt;();
//Create RecycleView object and pin view
RecyclerView recycleView = findViewById(R.id.linear_layout_with_recycleView_ID);
GridLayoutManager linearLayoutManager = new GridLayoutManager (this, 2);
//Setup Adapter
recycleView.setLayoutManager(linearLayoutManager);
recyclerAdapter = new MyRecycleAdapter(MainActivity.this, imageList);
recycleView.setAdapter(recyclerAdapter);
Log.d(TAG, &quot;onCreate: ------&gt;called&lt;-----&quot;);
//Creating reference for MyService and receiving deserialized data.
ApiService apiClient = ApiClient.getClient().create(ApiService.class);
Call&lt;List&lt;Pictures&gt;&gt; call = apiClient.getFile();
call.enqueue(new Callback&lt;List&lt;Pictures&gt;&gt;() {
@Override
public void onResponse(Call&lt;List&lt;Pictures&gt;&gt; call, Response&lt;List&lt;Pictures&gt;&gt; response) {
imageList = response.body();
Log.d(TAG, &quot;onResponse: ------&gt;called&lt;-----&quot;);
recyclerAdapter.setMyRecycleAdapter(imageList);
}
@Override
public void onFailure(Call&lt;List&lt;Pictures&gt;&gt; call, Throwable t) {
Log.d(&quot;TAG&quot;,&quot;onFailure = ------&gt;called&lt;----- &quot;+t.toString());
}
});
}

}

答案1

得分: 0

看起来我当时调用了错误的 API。应该是这样的:

public interface ApiService {

    @GET("/v2/list")
    Call<List<Pictures>> getFile();
}

而且对象类也有问题。由 http://www.jsonschema2pojo.org/ 生成:

public class Pictures {

    @SerializedName("id")
    @Expose
    private String id;

    @SerializedName("author")
    @Expose
    private String author;

    @SerializedName("width")
    @Expose
    private Integer width;

    @SerializedName("height")
    @Expose
    private Integer height;

    @SerializedName("url")
    @Expose
    private String url;

    @SerializedName("download_url")
    @Expose
    private String downloadUrl;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }
}

现在它能够正常工作,并在网格视图中显示出漂亮的随机图片。

英文:

It seems that I was asking wrong api. It should be

public interface ApiService {
@GET(&quot;/v2/list&quot;)
Call&lt;List&lt;Pictures&gt;&gt; getFile();

}

And object class was wrong. Generated by http://www.jsonschema2pojo.org/

public class Pictures {
@SerializedName(&quot;id&quot;)
@Expose
private String id;
@SerializedName(&quot;author&quot;)
@Expose
private String author;
@SerializedName(&quot;width&quot;)
@Expose
private Integer width;
@SerializedName(&quot;height&quot;)
@Expose
private Integer height;
@SerializedName(&quot;url&quot;)
@Expose
private String url;
@SerializedName(&quot;download_url&quot;)
@Expose
private String downloadUrl;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}

}

Now it works and displays nice random pictures in gridview.

huangapple
  • 本文由 发表于 2020年10月16日 05:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64379724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定