Custom Listview Using BaseAdapter With Image And Text In Android Example

Please follow and like us:

custom listview

 

In this example we are going to create custom listview with Base Adapter, here we create custom listview for single item which contains post details (post image, title, description and date). For lazy loading image we have used Image Loader class which allows to load images asynchronously. Here we get data in JSON format from URL, hence we have used GSON library for automatically JSON parsing in custom listview.

Let’s Explore Custom Listview Using BaseAdapter step by step

From This Single Example We Can Cover Following Topics:

  • Custom Listview with BaseAdapter
  • Lazy loading Image in custom Listview
  • JSON parsing using GSON library in custom listview

Create activity_my.xml layout file which contains listview for custom listview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity">
    <ListView
        android:id="@+id/postList"
        android:layout_width="match_parent"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp"
        android:layout_height="match_parent">
    </ListView>
</RelativeLayout>

Create item_view.xml layout file which contains view of single listview item for custom listview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_margin="4dp"
        android:scaleType="centerCrop"
        android:id="@+id/imgPost"
        android:layout_width="50dp"
        android:background="@android:color/darker_gray"
        android:padding="2dp"
        android:layout_height="match_parent" />
    <RelativeLayout
        android:padding="4dp"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content">
        <TextView
            android:singleLine="true"
            android:layout_toLeftOf="@+id/txtPostDate"
            android:id="@+id/txtPostTitle"
            android:layout_alignParentLeft="true"
            android:layout_width="wrap_content"
            android:text="Title"
            android:textStyle="bold"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/txtPostDate"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:text="Date"
            android:textColor="@android:color/darker_gray"
            android:textSize="18sp"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_below="@+id/txtPostTitle"
            android:id="@+id/txtPostDescription"
            android:layout_width="match_parent"
            android:text="Description"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            android:maxLines="3"
            android:layout_height="wrap_content" />
    </RelativeLayout>
</LinearLayout>

In JSON, “[” stands for JSON Array and “{” stands for JSON Object.We need to create one model class “BeanPost” and annotate field names with the SerializedName annotation. When we add serialized name to field must match with key name from JSON.

import com.google.gson.annotations.SerializedName;
public class BeanPost {

    @SerializedName("post_title")
    private String post_title;
    @SerializedName("post_date")
    private String post_date;
    @SerializedName("image_url")
    private String image_url;
    @SerializedName("description")
    private String description;

    public BeanPost(String post_title, String post_date, String image_url, String description) {
        this.post_title = post_title;
        this.post_date = post_date;
        this.image_url = image_url;
        this.description = description;
    }

    public String getPost_title() {
        return post_title;
    }
    public void setPost_title(String post_title) {
        this.post_title = post_title;
    }
    public String getPost_date() {
        return post_date;
    }
    public void setPost_date(String post_date) {
        this.post_date = post_date;
    }
    public String getImage_url() {
        return image_url;
    }
    public void setImage_url(String image_url) {
        this.image_url = image_url;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

Create API.java class to perform an HTTP request and retrieve the resource as a stream for custom listview

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class API {
                private static Reader reader=null;
                public static Reader getData(String SERVER_URL) {
                                try {
                                                DefaultHttpClient httpClient = new DefaultHttpClient();
                                                HttpPost httpPost = new HttpPost(SERVER_URL);
                                                HttpResponse response = httpClient.execute(httpPost);
                                                StatusLine statusLine = response.getStatusLine();
                                                if (statusLine.getStatusCode() == 200) {
                                                                HttpEntity entity = response.getEntity();
                                                                InputStream content = entity.getContent();
                                                                reader = new InputStreamReader(content);
                                                } else {
//  Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
                                                }
                                } catch (ClientProtocolException e) {
                                                e.printStackTrace();
                                } catch (IllegalStateException e) {
                                                e.printStackTrace();
                                } catch (IOException e) {
                                                e.printStackTrace();
                                }
                                return reader;
                }
}

For loading images from server we use DisplayImage() method from image loader class, you can find it in source code. Here we create PostAdapter as BaseAdapter for custom listview.

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import nkdroid.com.customlistview.image_loader.ImageLoader;
public class MyActivity extends Activity {
    private ProgressDialog progressDialog;
    private ListView postList;
    private ArrayList&lt;BeanPost&gt; beanPostArrayList;
    private PostAdapter postAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        postList=(ListView)findViewById(R.id.postList);
        new AsyncTask&lt;Void,Void,Void&gt;(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog=new ProgressDialog(MyActivity.this);
                progressDialog.setCancelable(false);
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }
            @Override
            protected Void doInBackground(Void... voids) {
                Reader reader=API.getData("http://beta.json-generator.com/api/json/get/KQiRLjN");
                Type listType = new TypeToken&lt;ArrayList&lt;BeanPost&gt;&gt;(){}.getType();
                beanPostArrayList = new GsonBuilder().create().fromJson(reader, listType);
                handleJsonData();
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                progressDialog.dismiss();
            }
        }.execute();
    }
    public void handleJsonData(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                postAdapter=new PostAdapter(MyActivity.this,beanPostArrayList);
                postList.setAdapter(postAdapter);
            }
        });
    }
    public class PostAdapter extends BaseAdapter {
        Context context;
        ArrayList&lt;BeanPost&gt; postArrayList;
        ImageLoader imageLoader;
        public PostAdapter(Context context, ArrayList&lt;BeanPost&gt; postArrayList) {
            imageLoader=new ImageLoader(MyActivity.this);
            this.context = context;
            this.postArrayList = postArrayList;
        }
        public int getCount() {
            return postArrayList.size();
        }
        public Object getItem(int position) {
            return postArrayList.get(position);
        }
        public long getItemId(int position) {
            return position;
        }
        class ViewHolder {
            TextView txtPostTitle,txtPostDate,txtPostDescription;
            ImageView imgPost;
        }
        public View getView(final int position, View convertView,ViewGroup parent) {
            final ViewHolder holder;
            LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_list, parent, false);
                holder = new ViewHolder();
                holder.txtPostTitle = (TextView) convertView.findViewById(R.id.txtPostTitle);
                holder.txtPostDate = (TextView) convertView.findViewById(R.id.txtPostDate);
                holder.txtPostDescription = (TextView) convertView.findViewById(R.id.txtPostDescription);
                holder.imgPost = (ImageView) convertView.findViewById(R.id.imgPost);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.txtPostTitle.setText(postArrayList.get(position).getPost_title());
            holder.txtPostDate.setText(postArrayList.get(position).getPost_date());
            holder.txtPostDescription.setText(postArrayList.get(position).getDescription());
            imageLoader.DisplayImage(postArrayList.get(position).getImage_url(),holder.imgPost);
            return convertView;
        }
    }
}

Do you like our simple tutorial about implementing custom listview with base adapter?

Share your review on post.. keep coding 🙂

nirav kalola