Search code examples
androidandroid-recyclerviewpicassoandroid-glide

Images not loading in RecyclerView using Picasso


I call one web service and I got one JSON which contains many data and after parsing this I tried to show three text in TextView and one image in ImageView in RecyclerView. In this data all the three TextView got its textual data from POJO but the Image is not loading. I tried it using both the Picasso and Glide library too. But it can't load the image from the server.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.recyclerviewdemo">

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

build.gradle

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"

defaultConfig {
    applicationId "com.example.recyclerviewdemo"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner 
    "android.support.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 
'proguard-rules.pro'
    }
}

packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
    }
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', 
{
    exclude group: 'com.android.support', module: 'support-annotations'
})
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'org.apache.httpcomponents:httpcore:4.2.4'
    compile 'org.apache.httpcomponents:httpmime:4.3'
    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_marginBottom="8dp"
    android:layout_height="match_parent"
    tools:context="com.example.recyclerviewdemo.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_service_provider_list"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="8dp" />

</LinearLayout>

service_provider_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:elevation="10dp"
        card_view:cardCornerRadius="3dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="4">

            <ImageView
                android:id="@+id/iv_profile_image"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_gravity="left"
                android:layout_marginRight="16dp"
                android:layout_weight="3" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_marginBottom="10dp"
                    android:text="Name"
                    android:textSize="20dp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/tv_address"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/title"
                    android:layout_marginBottom="5dp"
                    android:text="Address" />

                <TextView
                    android:id="@+id/tv_description"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/title"
                    android:maxLines="1"
                    android:text="Description" />

            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

private String TAG = "ServiceProviderList";
private ProgressDialog mProgressDialog;
private ArrayList<ServiceProvider> serviceProviderList;
private ServiceProviderAdapter mServiceProviderAdapter;
private RecyclerView rv_service_provider_list;
private RecyclerView.LayoutManager mLayoutManager;

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

    registerViews();
    init();

    rv_service_provider_list.setLayoutManager(mLayoutManager);
    rv_service_provider_list.setItemAnimator(new DefaultItemAnimator());
    rv_service_provider_list.setAdapter(mServiceProviderAdapter);

    fetchServiceProviderList();
}

private void fetchServiceProviderList() {
    mProgressDialog.setMessage("Downloading json...");
    mProgressDialog.show();

    JSONObject jsonParams = getJsonParams();
    CustomJsonObjectRequest req = new 
    CustomJsonObjectRequest(AppConfig.BASE_URL, jsonParams,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    mProgressDialog.hide();
                    JSONArray dataJSONArrayObj = null;
                    try {
                        dataJSONArrayObj = response.getJSONArray("data");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    serviceProviderList.clear();

                    for (int i = 0; i < dataJSONArrayObj.length(); i++) {
                        try {
                            JSONObject serviceProviderObjs = 
 dataJSONArrayObj.getJSONObject(i);
 ServiceProvider serviceProvider = new 
 ServiceProvider();

 serviceProvider.setServiceProviderId(Integer.parseInt
 (serviceProviderObjs.getString("service_provider_id").trim()));

 serviceProvider.setName(serviceProviderObjs.getString("name").trim());

 serviceProvider.setDescription(serviceProviderObjs.getString
 ("description").trim());

 serviceProvider.setLatitude(Double.parseDouble
 (serviceProviderObjs.getString("lat").trim()));

 serviceProvider.setLongitude(Double.parseDouble
 (serviceProviderObjs.getString("long").trim()));

 serviceProvider.setAddress(serviceProviderObjs.getString("address").
 trim());

 serviceProvider.setImage(serviceProviderObjs.getString("image").trim());

                            serviceProviderList.add(serviceProvider);
                        } catch (JSONException e) {
                            Log.e(TAG, "Json parsing error: " + 
 e.getMessage());
                        }
                    }

                    mServiceProviderAdapter.notifyDataSetChanged();

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error: " + error.getMessage());
            mProgressDialog.hide();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(req);
}

public JSONObject getJsonParams() {
    JSONObject rootJson = new JSONObject();
    try{
        rootJson.put("method", "service_provider_list");
        JSONObject jsonObject = new JSONObject();
        rootJson.put("params", jsonObject);
    } catch (Exception ex){
        ex.printStackTrace();
    }
    Log.d("JsonForming", rootJson.toString());
    return rootJson;
}

private void registerViews() {
    rv_service_provider_list = (RecyclerView) 
    findViewById(R.id.rv_service_provider_list);
}

private void init() {
    mProgressDialog = new ProgressDialog(this);
    serviceProviderList = new ArrayList<ServiceProvider>();
    mServiceProviderAdapter = new 
    ServiceProviderAdapter(serviceProviderList, MainActivity.this);
    mLayoutManager = new LinearLayoutManager(getApplicationContext());
}
}

ServiceProviderAdapter.java

public class ServiceProviderAdapter extends 
RecyclerView.Adapter<ServiceProviderAdapter.MyViewHolder> {

private Context mContext;
private ArrayList<ServiceProvider> serviceProviderList;
private ProgressBar mProgressDialog;

public ServiceProviderAdapter(ArrayList<ServiceProvider> 
serviceProviderList, Context mContext) {
    this.serviceProviderList = serviceProviderList;
    this.mContext = mContext;
    mProgressDialog = new ProgressBar(mContext);
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView tv_name, tv_address, tv_description;
    public ImageView iv_profile_image;

    public MyViewHolder(View view) {
        super(view);
        iv_profile_image = (ImageView) 
view.findViewById(R.id.iv_profile_image);
        tv_name = (TextView) view.findViewById(R.id.tv_name);
        tv_address = (TextView) view.findViewById(R.id.tv_address);
        tv_description = (TextView) view.findViewById(R.id.tv_description);
    }
}

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

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    ServiceProvider serviceProvider = serviceProviderList.get(position);

    /*Glide.with(mContext).load(serviceProvider.getImage())
            .thumbnail(0.5f)
            .crossFade()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(holder.iv_profile_image);*/

    Picasso.with(mContext).load(serviceProvider.getImage())
        .fit()
        .centerCrop()
        .into(holder.iv_profile_image);

    holder.tv_name.setText(serviceProvider.getName());
    holder.tv_address.setText(serviceProvider.getAddress());
    holder.tv_description.setText(serviceProvider.getDescription());
    Log.d("ServiceProviderAdapter", "Adapting Data to Views");
}

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

Output is coming like this


Solution

  • I had problems in the past with Glide and RecyclerViews when not using Placeholders. I recommend to use a placeholder.

        Glide.with(mContext).load(serviceProvider.getImage())
            .thumbnail(0.5f)
            .crossFade()
            .placeholder(R.drawable.placeholder)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(holder.iv_profile_image);