我想用我的 SQLite 数据库中的条目填充我的 Gridview,但它不起作用。
在我的主要活动中,我为 gridview 设置了一个适配器:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.room_layout);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new RoomImageAdapter(this));
Button addRoom = (Button) findViewById(R.id.addRoom);
//OnClickListener for room button
addRoom.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
addDeviceOrRoom();
}
});
}
RoomImageAdapter 类如下所示:
public class RoomImageAdapter extends BaseAdapter {
private Context mContext;
private static SQLiteDatabaseAdapter dbHelper;
private static int i=0;
public RoomImageAdapter(Context c) {
mContext= c;
}
@Override
public int getCount() {
// defines how many items in the gridview are shown
return 7;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
readDatabase();
if(convertView==null){
LayoutInflater li = LayoutInflater.from(mContext);
v = li.inflate(R.layout.imageandtextforgrid, null);
TextView tv = (TextView)v.findViewById(R.id.icon_text);
tv.setText("Raum: "+position);
ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
iv.setImageResource(R.drawable.livingroom);
}
else
{
v = convertView;
}
return v;
}
public void readDatabase(){
Log.d("DB", "Start DB read");
String name;
dbHelper = new SQLiteDatabaseAdapter(mContext);
dbHelper.open();
Cursor cursor = dbHelper.getRoomName();
cursor.moveToFirst();
if(! cursor.isAfterLast()) {
do {
name= cursor.getString(1);
Log.d("DB", "RoomName is: "+name);
} while (cursor.moveToNext());
}
cursor.close();
dbHelper.close();
Log.d("DB", "Stop DB read");
}
}
我的 SQLite 数据库中的代码是:
/**
* GetRoomName
*/
public Cursor getRoomName() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
null, null, null, null, null, null},
null, null, null, null, KEY_ROOMNAME);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
但是name= cursor.getString(1);
RoomImageAdapter 内的行永远不会执行,并且光标似乎为空。任何人的想法?