使用SimpleCursorAdapter从SQL填充ListView

时间:2015-03-29 18:32:00

标签: java android sql listview simplecursoradapter

我正在尝试使用SimpleCursorAdapter使用从SQLite数据库检索的数据填充ListView。我们用于表的KEY是;

_ROWID - 表示行号(在ListView中不可见)

_NAME - 我们数据库中的食品名称(如面包或奶酪)

_AMOUNT - 您对此食品的数量

_DATE - 产品的失效日期

另一个小组成员为数据库编写了代码,大约一半时间有一个名为getData的公共String。代码看起来像这样;

public class DatabaseCustom {

public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DATE = "expiration_date";

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_AMOUNT, KEY_DATE};

private static final String DATABASE_NAME = "customDb";
private static final String DATABASE_TABLE = "customTable";
private static final int DATABASE_VERSION = 1;

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 " + DATABASE_TABLE + " (" + KEY_ROWID
                + " INTEGER PRIMARY_KEY, " + KEY_NAME + " TEXT NOT NULL, "
                + KEY_AMOUNT + " TEXT NOT NULL, " + KEY_DATE
                + "TEXT NOT NULL);");
    }

    @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 DatabaseCustom(Context c) {
    ourContext = c;
}

public DatabaseCustom open() {
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

public void close() {
    ourHelper.close();
}

public long createEntry(String name, String amount, String date) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(KEY_NAME, name);
    cv.put(KEY_AMOUNT, amount);
    cv.put(KEY_DATE, date);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);
}

public String getData() {
    // TODO Auto-generated method stub
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
            KEY_DATE };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
            null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iAmount = c.getColumnIndex(KEY_AMOUNT);
    int iDate = c.getColumnIndex(KEY_DATE);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        result = result + c.getString(iRow) + " " + c.getString(iName)
                + " " + c.getString(iAmount) + " " + c.getString(iDate)
                + "\n";
    }
    return result;
}

public String getName(long l) {
    // TODO Auto-generated method stub
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
            KEY_DATE };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
            + l, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
        String name = c.getString(1);
        return name;
    }
    return null;
}

public String getAmount(long l) {
    // TODO Auto-generated method stub
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
            KEY_DATE };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
            + l, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
        String name = c.getString(2);
        return name;
    }
    return null;
}

public String getDate(long l) {
    // TODO Auto-generated method stub
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AMOUNT,
            KEY_DATE };
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
            + l, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
        String name = c.getString(3);
        return name;
    }
    return null;
}

public void updateEntry(long lRow, String mName, String mAmount,
        String mDate) {
    // TODO Auto-generated method stub
    ContentValues cvUpdate = new ContentValues();
    cvUpdate.put(KEY_NAME, mName);
    cvUpdate.put(KEY_AMOUNT, mAmount);
    cvUpdate.put(KEY_DATE, mDate);
    ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow,
            null);
}

public void deleteEntry(long lRow1) {
    // TODO Auto-generated method stub
    ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}

从我收集的内容中,我需要在显示此ListView的Activity的代码中使用SimpleCursorAdapter设置populateListView方法。这是我到目前为止的代码(省略了一些与我的问题无关的代码);

public class Products extends Activity implements OnClickListener{

DatabaseCustom ourDb;
final Context context = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.products);

    openDb();
    initiate();
    populateListView();
}

public void onClick(View v) {
    switch (v.getId()){
        //A few different buttons for this activity here
    }   
}

private void initiate(){
    //Link all the java variables to the corresponding xml elements here
}

private void openDb(){
    ourDb = new DatabaseCustom(this);
    ourDb.open();
}

private void populateListView(){
    Cursor cursor = ourDb.getData();
    String[] fromFieldNames = new String[] {DatabaseCustom.KEY_NAME, DatabaseCustom.KEY_AMOUNT, DatabaseCustom.KEY_DATE};
    int[] toViewIDs = new int[] {R.id.tvProductNameList, R.id.tvAmountList, R.id.tvDateList};
    SimpleCursorAdapter ourCursorAdapter;
    ourCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);//Put text from KEYS into TVs
    ListView ourList = (ListView) findViewById(R.id.lvProducts);
    ourList.setAdapter(ourCursorAdapter);           
}

在populateListView方法中,我尝试创建一个游标,在我们的数据库中查找getData方法并逻辑地给出错误,因为此数据库中的getData方法是公共String而不是公共游标,所以我尝试创建一个而是公共Cursor,我编码如下;

public Cursor getData() {
    String where = null;
    Cursor c =  ourDatabase.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

在为private void populateListView和公共Cursor添加代码之后,获取数据Eclipse并不显示任何错误,但应用程序在加载应该显示ListView的活动时崩溃。

在关注了SQL数据库,ListViews,CursorAdapters和String Arrays的大量教程之后,我已经到了我不知道在哪里寻找答案的地步,所以任何帮助都会非常受欢迎。

0 个答案:

没有答案