我很难找到一种从数据库中填充列表视图的方法。
这是我的代码:
SQLDatabase.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLDatabase {
public static final String KEY_MOVENAME = "movename";
public static final String KEY_MOVEID = "_moveid";
public static final String KEY_MOVEDATE = "movedate";
private static final String DATABASE_NAME = "mymovingfriend";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_TABLE = "movingname";
public static final String CREATE_TABLE = "CREATE TABLE " + DATABASE_TABLE + " (" + KEY_MOVEID +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_MOVEDATE + " TEXT NOT NULL, " + KEY_MOVENAME + " TEXT NOT NULL);";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public SQLDatabase(Context c){
ourContext = c;
}
public SQLDatabase open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createMove(String smovename){
ContentValues cv = new ContentValues();
cv.put(KEY_MOVENAME, smovename);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getMove(){
String[] column = new String[]{KEY_MOVENAME};
Cursor c = ourDatabase.query(DATABASE_TABLE, column, null, null, null, null, null);
String result = "";
int iMove = c.getColumnIndex(KEY_MOVENAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iMove) + "\n";
}
c.close();
return result;
}
}
这是我的列表视图类,基本上这是列表视图与数据库分开的类。
ListMovingNames.java
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
public class ListMovingNames extends ListActivity {
ListView MoveList;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectorcreatemove);
MoveList = (ListView) findViewById(R.id.lvMoveItems);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
}
我想要做的是填充列表视图并在从列表中选择一个项目时执行特定任务。