{"id":670,"date":"2024-06-12T09:26:38","date_gmt":"2024-06-12T09:26:38","guid":{"rendered":"https:\/\/robotqa.com\/blog\/?p=670"},"modified":"2024-06-12T09:26:38","modified_gmt":"2024-06-12T09:26:38","slug":"best-way-to-download-images-and-show-in-data-adapter-in-android","status":"publish","type":"post","link":"https:\/\/robotqa.com\/blog\/best-way-to-download-images-and-show-in-data-adapter-in-android\/","title":{"rendered":"Best Way to Download Images and Show in Data Adapter in Android"},"content":{"rendered":"<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/blog.robotqa.com\/wp-content\/uploads\/2024\/06\/202406120918468.webp\" alt=\"andorid-recycler-view\n\" width=\"720\" height=\"1280\" class=\"aligncenter size-full wp-image-672\" srcset=\"https:\/\/blog.robotqa.com\/wp-content\/uploads\/2024\/06\/202406120918468.webp 720w, https:\/\/blog.robotqa.com\/wp-content\/uploads\/2024\/06\/202406120918468-169x300.webp 169w, https:\/\/blog.robotqa.com\/wp-content\/uploads\/2024\/06\/202406120918468-576x1024.webp 576w\" sizes=\"auto, (max-width: 720px) 100vw, 720px\" \/>\n<p><\/p>\nDownloading images and displaying them efficiently in an Android application is a common requirement, especially for apps dealing with media, social networks, or e-commerce. Utilizing third-party HTTP client libraries can greatly simplify this process. In this blog, we will explore the best practices for downloading images and showing them in a data adapter using Retrofit and Glide, two popular libraries in Android development.\n<p><\/p>\n<h2><strong>Introduction<\/strong><\/h2>\nWhen building Android applications that need to download and display images, handling the network operations efficiently and ensuring smooth user experience is crucial. Retrofit is a powerful type-safe HTTP client for Android, while Glide is a fast and efficient image loading library. Together, they provide an excellent solution for this task.\n<p><\/p>\n<h2><strong>Setting Up Your Project<\/strong><\/h2>\nFirst, ensure that your project includes the necessary dependencies for Retrofit and Glide.\n\n<strong>build.gradle (Module: app)<\/strong>\n<pre class=\"lang:xhtml decode:true \">dependencies {\n    implementation 'com.squareup.retrofit2:retrofit:2.9.0'\n    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'\n    implementation 'com.github.bumptech.glide:glide:4.12.0'\n    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'\n}\n<\/pre>\n<p><\/p>\n<h2><strong>Creating the Retrofit Client<\/strong><\/h2>\nRetrofit is used to define and manage network requests in a clean and straightforward way.\n<p><\/p>\n<h3><strong>API Interface<\/strong><\/h3>\nCreate an interface to define your API endpoints.\n<pre class=\"lang:java decode:true \">public interface ApiService {\n    @GET(\"photos\")\n    Call&lt;List&lt;Photo&gt;&gt; getPhotos();\n}\n<\/pre>\n<p><\/p>\n<h3><strong>Retrofit Instance<\/strong><\/h3>\nCreate a singleton instance of Retrofit to manage network requests.\n<pre class=\"lang:java decode:true \">public class ApiClient {\n    private static final String BASE_URL = \"https:\/\/api.example.com\/\";\n    private static Retrofit retrofit = null;\n\n    public static Retrofit getClient() {\n        if (retrofit == null) {\n            retrofit = new Retrofit.Builder()\n                    .baseUrl(BASE_URL)\n                    .addConverterFactory(GsonConverterFactory.create())\n                    .build();\n        }\n        return retrofit;\n    }\n}\n<\/pre>\n<p><\/p>\n<h2><strong>Creating the Data Model<\/strong><\/h2>\nDefine a data model to map the JSON response.\n<pre class=\"lang:java decode:true \">public class Photo {\n    @SerializedName(\"id\")\n    private int id;\n\n    @SerializedName(\"title\")\n    private String title;\n\n    @SerializedName(\"url\")\n    private String url;\n\n    \/\/ Getters and Setters\n}\n<\/pre>\n<p><\/p>\n<h2><strong>Setting Up the RecyclerView Adapter<\/strong><\/h2>\nCreate an adapter for your RecyclerView to bind the photo data to the UI components.\n<p><\/p>\n<h3><strong>PhotoAdapter.java<\/strong><\/h3>\n<pre class=\"lang:java decode:true \">public class PhotoAdapter extends RecyclerView.Adapter&lt;PhotoAdapter.PhotoViewHolder&gt; {\n    private List&lt;Photo&gt; photos;\n    private Context context;\n\n    public PhotoAdapter(Context context, List&lt;Photo&gt; photos) {\n        this.context = context;\n        this.photos = photos;\n    }\n\n    @Override\n    public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n        View view = LayoutInflater.from(context).inflate(R.layout.photo_item, parent, false);\n        return new PhotoViewHolder(view);\n    }\n\n    @Override\n    public void onBindViewHolder(PhotoViewHolder holder, int position) {\n        Photo photo = photos.get(position);\n        holder.title.setText(photo.getTitle());\n        Glide.with(context)\n                .load(photo.getUrl())\n                .placeholder(R.drawable.placeholder)\n                .into(holder.imageView);\n    }\n\n    @Override\n    public int getItemCount() {\n        return photos.size();\n    }\n\n    public static class PhotoViewHolder extends RecyclerView.ViewHolder {\n        ImageView imageView;\n        TextView title;\n\n        public PhotoViewHolder(View itemView) {\n            super(itemView);\n            imageView = itemView.findViewById(R.id.photo_image);\n            title = itemView.findViewById(R.id.photo_title);\n        }\n    }\n}\n<\/pre>\n<p><\/p>\n<h2><strong>Creating the Layout Files<\/strong><\/h2>\nDefine the layout for each photo item and the main activity layout.\n<h3><strong>res\/layout\/photo_item.xml<\/strong><\/h3>\n<pre class=\"lang:xhtml decode:true \">&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"vertical\"\n    android:padding=\"8dp\"&gt;\n\n    &lt;ImageView\n        android:id=\"@+id\/photo_image\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"200dp\"\n        android:scaleType=\"centerCrop\" \/&gt;\n\n    &lt;TextView\n        android:id=\"@+id\/photo_title\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"wrap_content\"\n        android:paddingTop=\"4dp\"\n        android:textSize=\"16sp\" \/&gt;\n&lt;\/LinearLayout&gt;\n<\/pre>\n<p><\/p>\n<h3><strong>res\/layout\/activity_main.xml<\/strong><\/h3>\n<pre class=\"lang:xhtml decode:true \">&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"&gt;\n\n    &lt;androidx.recyclerview.widget.RecyclerView\n        android:id=\"@+id\/recycler_view\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:padding=\"8dp\"\n        android:scrollbars=\"vertical\" \/&gt;\n&lt;\/RelativeLayout&gt;\n<\/pre>\n<p><\/p>\n<h2><strong>Fetching Data and Displaying in RecyclerView<\/strong><\/h2>\nIn your main activity, fetch the photo data from the API and set up the RecyclerView.\n<p><\/p>\n<h3><strong>MainActivity.java<\/strong><\/h3>\n<pre class=\"lang:java decode:true \">public class MainActivity extends AppCompatActivity {\n\n    private RecyclerView recyclerView;\n    private PhotoAdapter photoAdapter;\n    private List&lt;Photo&gt; photoList;\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        recyclerView = findViewById(R.id.recycler_view);\n        recyclerView.setLayoutManager(new LinearLayoutManager(this));\n\n        photoList = new ArrayList&lt;&gt;();\n        photoAdapter = new PhotoAdapter(this, photoList);\n        recyclerView.setAdapter(photoAdapter);\n\n        fetchPhotos();\n    }\n\n    private void fetchPhotos() {\n        ApiService apiService = ApiClient.getClient().create(ApiService.class);\n        Call&lt;List&lt;Photo&gt;&gt; call = apiService.getPhotos();\n\n        call.enqueue(new Callback&lt;List&lt;Photo&gt;&gt;() {\n            @Override\n            public void onResponse(Call&lt;List&lt;Photo&gt;&gt; call, Response&lt;List&lt;Photo&gt;&gt; response) {\n                if (response.isSuccessful() &amp;&amp; response.body() != null) {\n                    photoList.addAll(response.body());\n                    photoAdapter.notifyDataSetChanged();\n                }\n            }\n\n            @Override\n            public void onFailure(Call&lt;List&lt;Photo&gt;&gt; call, Throwable t) {\n                Toast.makeText(MainActivity.this, \"Failed to load photos\", Toast.LENGTH_SHORT).show();\n            }\n        });\n    }\n}\n<\/pre>\n<!-- CTA Section -->\n<p>&nbsp;<\/p>\n<div class=\"bg-primary text-white text-center\">\n<div class=\"container space-1\"><span class=\"h6 d-block d-lg-inline-block font-weight-light mb-lg-0\"> <span class=\"font-weight-semi-bold\">Need Debugging?<\/span> \u2013 Try RobotQA and Start Debugging on Real Devices. <\/span> <a class=\"btn btn-sm btn-white transition-3d-hover font-weight-normal ml-3\" href=\"https:\/\/plugins.jetbrains.com\/plugin\/24460-robotqa-real-device-debugging-on-cloud\">Download Plugin<\/a><\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<!-- End CTA Section -->\n<p><\/p>\n<h2><strong>Conclusion<\/strong><\/h2>\nBy using Retrofit and Glide together, you can efficiently download images and display them in a RecyclerView. Retrofit handles the network operations, while Glide handles image loading and caching. This combination ensures that your application is responsive and provides a smooth user experience. Following these best practices will help you create a more robust and maintainable Android application.","protected":false},"excerpt":{"rendered":"<p>Downloading images and displaying them efficiently in an Android application is a common requirement, especially for apps dealing with media, social networks, or e-commerce. Utilizing third-party HTTP client libraries can greatly simplify this process. In this blog, we will explore&#8230;<\/p>\n","protected":false},"author":1,"featured_media":672,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19],"tags":[39],"class_list":["post-670","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-app-debugging","tag-android-development"],"_links":{"self":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/posts\/670","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/comments?post=670"}],"version-history":[{"count":0,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/posts\/670\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/media\/672"}],"wp:attachment":[{"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/media?parent=670"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/categories?post=670"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/robotqa.com\/blog\/wp-json\/wp\/v2\/tags?post=670"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}