12

I am interested in creating a generic BaseAdapter which will apply to any ListView having any list_item . And it will set the item_row for the list_view.

    public class GenericAdapter extends BaseAdapter
    {

    Context context;

    ArrayList<HashMap<String, String>> list;

    LayoutInflater inflater;

    public GenericAdapter (Context context, ArrayList<HashMap<String, String>> list) 
        {
            this.context = context;

            this.list = list;

            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public Object getItem(int position)
        {   
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {   
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view = convertView;

          if(view == null)
           {
            view = inflater.inflate(R.layout.item_of_any_list, parent, false);

// i have to do something here like there may be a method which must be call 

           }

            /*HashMap<String, String> map = list.get(position);

            TextView textViewName = (TextView) view.findViewById(R.id.name);

            TextView textViewDate = (TextView) view.findViewById(R.id.date);

            //TextView textViewDesc = (TextView) view.findViewById(R.id.desc);

            textViewName.setText(map.get("name"));

            textViewDate.setText(map.get("date"));

            //textViewDesc.setText(map.get("description"));
    */      
            return view;
        }

I think i have to create an interface that's get and set the item_row for individual item. But i don't know it may be possible . Can someone tell me how i can achieve it.

My idea is to create an interface and GenericAdapter implements that interface. In that interface there is a method to get and set the item_row. Any class which extends GenericAdapter must implement that method. it will help us make a generic adapter.

When we extend that adapter we don't need to write all code like getCount, getItem,getItemId, we just have to override a function which is to inflateLayout. which must be inside getView

Thanks in Advance

2

4 Answers 4

19

Answering my own Question after two years.

In order to make Generic Adapter you need abstract methods in parent class which should be implemented by child. So GenericAdapter must be Abstract and create abstract methods for data you want to change.

I have different types of ArrayList to show in Adapter only it's model class is different. So I decided to write a genericAdapter. This is for recyclerview if someOne interested for listview. Let me know.

GenericAdapter

public abstract class GenericAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private ArrayList<T> items;

    public abstract RecyclerView.ViewHolder setViewHolder(ViewGroup parent);

    public abstract void onBindData(RecyclerView.ViewHolder holder, T val);

    public GenericAdapter(Context context, ArrayList<T> items){
        this.context = context;
        this.items = items;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder = setViewHolder(parent);
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        onBindData(holder,items.get(position));
    }

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

    public void addItems( ArrayList<T> savedCardItemz){
        items = savedCardItemz;
        this.notifyDataSetChanged();
    }

    public T getItem(int position){
        return items.get(position);
    }
}

And I use it like

     adapter = new GenericAdapter<DataModel>(context,modelList) {
        @Override
        public RecyclerView.ViewHolder setViewHolder(ViewGroup parent) {
            final View view =            LayoutInflater.from(context).inflate(R.layout.item_view_holder, parent, false);
            ItemViewHolder viewHolder = new ItemViewHolder(context, view);
            return viewHolder;
        }

        @Override
        public void onBindData(RecyclerView.ViewHolder holder1, DataModel val) {
                DataModel userModel = val;

                ItemViewHolder holder = (ItemViewHolder)holder1;
                holder.name.setText(userModel.getName());
                holder.fatherName.setText(userModel.getFatherName());
        }
    };
    mRecyclerView.setAdapter(adapter);

RecyclerView with Search sort functionality

3
  • @Nepster your code doesn't work for multiple types adapter. Actually, I can see it doesn't enough 'generic'. Your abstract methods are nothing than wrapper methods from RecycleView Adapter (setViewHolder is a wrapper of onCreateViewHolder, onBindData is wrapping for onBindViewHolder) This pattern will work for Adapter ListView instead of Recycle Adapter. Just my though
    – ductran
    Commented Feb 3, 2017 at 13:50
  • @R4j Give suggestion to improve it. And how can I implement generic filter on the basis of type Commented Feb 3, 2017 at 14:02
  • 1
    May be it helps codereview.stackexchange.com/questions/173504/… Commented Dec 9, 2017 at 19:15
1

I have created a generic adapter, the aar and the sources are at this url:

it's easy usage:

RecyclerAdapter<Customer> mAdapter = new RecyclerAdapter(customerList, CustomerViewHolder.class);

see Url link more details

1
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

public abstract class GenericAdapter<T> extends BaseAdapter {
    LayoutInflater layoutInflater;
    Context context;
    private List<T> tList;



public GenericAdapter(Context context, List<T> tList) {
        this.context = context;
        this.tList = tList;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        if (tList == null)
            return 0;
        return tList.size();
    }

    @Override
    public Object getItem(int position) {
        return tList.get(position);
    }


    @Override
    public long getItemId(int position) {
        return 0;
    }

    public abstract View getMyView(int position, View convertView, ViewGroup parent,T t);

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getMyView(position, convertView, parent,tList.get(position));
    }

}

and you can use it like

spnDistrict.setAdapter(new GenericAdapter<Institutions>(getContext(), institutionsList) {
            @Override
            public View getMyView(int position, View convertView, ViewGroup parent, Institutions institutions) {
                TextView textView = (TextView) convertView;
                if (textView == null) {
                    textView = (TextView) getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
                    textView.setTextColor(getContext().getResources().getColor(R.color.black));
                }
                textView.setText(institutions.getName());
                return textView;
            }
        });
1
  • While this may answer the question, it is better to explain the essential parts of the answer and possibly what was the problem with OPs code.
    – pirho
    Commented Dec 8, 2017 at 12:58
-1
import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.accel.cloudRDB.model.OpenTask;

public class Open_task_fragment extends Fragment {
    View view;
    ListView mListView;
    Open_task_adapter open_task_adapter;
    Context mContext;
    ArrayList<OpenTask> items;
    Button main_menu;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
    {

        mContext=getActivity();
        view=inflater.inflate(R.layout.open_task_layout, container,false);
        items=new ArrayList<OpenTask>();
        initXML();
        OpenTask open=new OpenTask();
         open.setDate("10/10/2014");
         open.setTime("12:00 pm");
         open.setAddress("chennai Dlf,Accel@123");
         open.setStatus("Deliver ABC");
         OpenTask open1=new OpenTask();
         open1.setDate("10/10/2014");
         open1.setTime("12:00 pm");
         open1.setAddress("chennai Dlf,Accel@123");
         open1.setStatus("Deliver ABC2");
         items.add(open);
         items.add(open1);
         open_task_adapter=new Open_task_adapter(mContext,items);
//      open_task_adapter=new Open_task_adapter(mContext,items);
        mListView.setAdapter(open_task_adapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int position,
                    long arg3) {

                    Intent intent=new Intent(mContext,Task_detail_activity.class);
                    ((Activity)mContext).startActivity(intent);
            }

        });
        return view;
    }
    public void initXML()
    {
        mListView=(ListView)view.findViewById(R.id.listView1);
        main_menu=(Button)view.findViewById(R.id.main_menu);
    }

}

model:

public class OpenTask {

    String Date,Time,Address,Status;

    public String getDate() {
        return Date;
    }

    public void setDate(String date) {
        Date = date;
    }

    public String getTime() {
        return Time;
    }

    public void setTime(String time) {
        Time = time;
    }

    public String getAddress() {
        return Address;
    }

    public void setAddress(String address) {
        Address = address;
    }

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }

}

adapter:

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;


public class Open_task_adapter extends BaseAdapter {

    Context context;

    ArrayList<OpenTask> list;

    public Open_task_adapter(Context context,ArrayList<OpenTask> list) {

        this.context = context;
        this.list = list;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        OpenTaskHolder hodler;
        LayoutInflater inflater;
        OpenTask open=list.get(position);
        if (convertView == null) 
        {
            inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.open_task_list_item_layout, null);
            hodler = new OpenTaskHolder();
            hodler.date = (TextView)convertView.findViewById(R.id.Date);
            hodler.time = (TextView)convertView.findViewById(R.id.Time);
            hodler.address = (TextView)convertView.findViewById(R.id.Address);
            hodler.status = (TextView)convertView.findViewById(R.id.Status);

            convertView.setTag(hodler);
        } else {
            hodler = (OpenTaskHolder)convertView.getTag();
        }

        hodler.date.setText(open.getDate());
        hodler.time.setText(open.getTime());
        hodler.address.setText(open.getAddress());
        hodler.status.setText(open.getStatus());

        return convertView;
    }

    class OpenTaskHolder {
        TextView date,time,address,status;
    }
}
3
  • 7
    Please explain how this answers the question. Commented Jul 4, 2014 at 10:24
  • @CommonsWare we can acheive in this way
    – learner
    Commented Jul 4, 2014 at 10:56
  • lazy cowards,down voter give comment what did i wrong from here?
    – learner
    Commented Jul 4, 2014 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.