0

I am trying to add an image next to each item in my ListView but without any success so far. There is a DB, from where I retrieve the text data, like this:

Cursor categoriesCursor = myCategoryData.getCategoriesData();

    String[] displayCategories = new String[]{ CategoryDataSource.NAME};
    int[] displayViews = new int[]{R.id.list_name};


    setListAdapter(new SimpleCursorAdapter(
            this,
            R.layout.list_category,
            categoriesCursor,
            displayCategories,
            displayViews,1));

    myListView = getListView();

Then I create an array to store the image IDs

Integer[] imageIds = new Integer[]{
                R.drawable.cat1,
                R.drawable.cat2,
                R.drawable.cat3,
        };

What I cannot figure out is how to bind them together. Thanks a lot for the help!

Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
VyaraG
  • 101
  • 11

1 Answers1

1

First make a data model :

public class dataModel {
String title;
int imageId;

public dataModel(String title, int imageId) {
    this.title = title;
    this.imageId = imageId;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public int getImageId() {
    return imageId;
}

public void setImageId(int imageId) {
    this.imageId = imageId;
}
}

then make a custom adapter :

public class adapter extends BaseAdapter{
ArrayList<dataModel> allItems=new ArrayList<>();
Context mContext;
public adapter(Context ct, ArrayList<dataModel> allItems) {
    this.allItems = allItems;
    mContext=ct;
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // YOU SHOULD INFLATE A VIEW HERE
    View mView=View.inflate(mContext,R.id.YOUR_VIEW_ID,null);
    TextView mText= .... ;
    ImageView mImage= ... ;

    dataModel mModel=(dataModel) getItem(position);
    mText.setText(mModel.getTitle());
    mImage.setImageResource(mModel.getImageId());

    return mView;
}
}

in your activity do this:

 String[] displayCategories = new String[]{ CategoryDataSource.NAME};
int[] displayViews = new int[]{R.id.list_name};

// make an array list of dataModel Items
ArrayList<dataModel> data=new ArrayList<dataModel>();
for(int i=0;i<displayCategories.length;i++){
    data.add(new dataModel(displayCategories[i],displayViews[i]));
}

setListAdapter(new adapter(this,data));
Omid Heshmatinia
  • 5,089
  • 2
  • 35
  • 50