我在MainActivity上有Listview。在Listview上必须图像和文本。我写查询并成功显示文本。我创建了扩展BaseAdapter的ListCategoryAdapter。 Internet中有数组的所有教程,都没有使用DB。这是适配器。
public class ListCategoryAdapter extends BaseAdapter{
LayoutInflater inflater;
List<Category> cats;
Context context;
DbHelper dbHelper;
String stt;
RecordHolder holder = null;
public ListCategoryAdapter(Context context1, List<Category> list){
if (list != null){
this.cats = list;
this.context = context1;
inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
@Override
public int getCount() {
return cats.size();
}
@Override
public Object getItem(int position) {
return cats.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
ImageView imageView2;
TextView txtCateg;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = inflater.inflate(R.layout.list_cat_adapter, null);
}
holder = new RecordHolder();
final Category cat = cats.get(position);
holder.txtCateg = (TextView)convertView.findViewById(R.id.txtCateg);
holder.txtCateg.setText(cat.getTitle());
holder.imageView2 = (ImageView) convertView.findViewById(R.id.imageView2);
holder.imageView2.setImageResource(cat.getImage());
return convertView;
}
static class RecordHolder{
TextView txtCateg;
ImageView imageView2;
}
}
这是数据库,其中来自调用文本和图像
public List<Category> categories(){
SQLiteDatabase db = this.getReadableDatabase();
List<Category> categoryList = new ArrayList<Category>();
String ss = "select * from category";
Cursor cursor = db.rawQuery(ss, null);
if (cursor.moveToFirst()) {
do {
Resources resources = mContext.getResources();
Category category = new Category();
category.setId(cursor.getInt(0));
category.setTitle(cursor.getString(1));
category.setImage(cursor.getInt(2));
categoryList.add(category);
} while (cursor.moveToNext());
} db.close();
return categoryList;
}
这是Category class
public class Category {
int id;
int image;
String title;
public Category(int image, String title, int id) {
super();
this.id = id;
this.image = image;
this.title = title;
}
public Category() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}