将选定的listView和editText作为一行添加到SQlite db

时间:2014-03-17 17:37:38

标签: android sqlite listview android-listview

我启动了一个新的活动,应该将addRow添加到db(两个字段:ListView项目标题和editText中的条目)。检索mainActivity上的行时,它只显示一列,这意味着只添加了一个字段。 如何将单击的listView项存储到db? 将editText值添加到db?

有什么问题

这是addRow代码:

Intent i = this.getIntent();
dataView.setText(i.getCharSequenceExtra("new item"));
mydManager = new DatabaseManager(this);

    okButton.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            Intent i = ListItemActivity.this.getIntent();        
            mydManager.addRow("Meat",dataView.getText().toString());//replace "meat" with selected listView item
            mydManager.close();
            ListItemActivity.this.setResult(RESULT_OK, i);
            finish();
        }
    });

这是DatabaseManager Class的addRow方法:

public boolean addRow(String g, String sub){
    ContentValues newEntry = new ContentValues();
    newEntry.put("Grocery", g); 
    newEntry.put("Sub_grocery", sub);         
    try{db.insertOrThrow(DB_TABLE, null, newEntry);}
    catch(Exception e) {
        Log.e("Error in inserting rows ", e.toString());
        e.printStackTrace();
        return false;           
    }
    db.close();
    return true;
}

这是来自databaseManager类的检索行方法:

public ArrayList<String> retrieveRows(String listViewItem){//selected listView as argument "ex: Meat"
    ArrayList<String> productRows=new ArrayList<String>();
    String[] columns = new String[]{"Grocery", "Sub_grocery"};
    String[] whereArgs = new String[]{listViewItem};
    Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        productRows.add(cursor.getString(0) + ", "+cursor.getString(1)+", ");
        cursor.moveToNext();
    }  
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    return productRows;
}

这里是如何创建表的:

private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (Grocery TEXT, Sub_grocery TEXT);";
@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

1 个答案:

答案 0 :(得分:0)

尝试像这样检索它,并检查你的日志猫。

           String selectQuery = "SELECT * FROM " + DB_TABLE;
       SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

           if (cursor.moveToFirst())
    {
        do
        {   
                          Log.d("database",cursor.getString(0));
                          Log.d("database",cursor.getString(1));
                     }
              while (cursor.moveToNext());
    }