在我的应用程序中,我有一个SQLite数据库来存储信息。在开始我的主要活动时,我初始化数据库。这是数据库的onCreate代码:
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_OWES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_DESC + " TEXT, " +
COLUMN_VALUE + " INTEGER" + ");";
db.execSQL(query);
}
我有一个按钮和两个editText字段,用于将信息发送到数据库并添加它。按下按钮时触发的活动中的代码:
public void addAnOwe(View v){
EditText description = (EditText) findViewById(R.id.descriptionAdd);
EditText value = (EditText) findViewById(R.id.valueAdd);
Owe newOwe = new Owe(description.getText().toString(), Integer.parseInt(value.getText().toString()));
DB.addOwe(newOwe);
Log.i(TAG, "Attempting to add Owe");
updateLists();
}
public void updateLists(){
descriptionList = DB.DBtoArray("desc");
valueList = DB.DBtoArray("value");
oweAdapter.updateValues(valueList);
oweAdapter.updateDescriptions(descriptionList);
updateTotalViewText();
}
DBManager中的代码:
public void addOwe(Owe owe){
ContentValues values = new ContentValues();
String description = owe.get_desc();
String value = String.valueOf(owe.get_value());
values.put(COLUMN_DESC, description);
values.put(COLUMN_VALUE, value);
Log.i(TAG, "Attempting to add: " + description + " - " + value);
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_OWES, null, values);
db.close();
}
此时所有日志消息都显示DBManager正在正确接收描述和值。但是,我使用两种方法从数据库中读取信息。第一个,我自己写道:
public String[] DBtoArray(String column){
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_OWES + " WHERE 1", null);
String[] array = new String[c.getCount()];
int i = 0;
while(c.moveToNext()){
array[i] = c.getString(c.getColumnIndex(column));
i++;
}
Log.i(TAG, "String of db is " + databaseToString());
Log.i(TAG, "Array Log is " + Arrays.toString(array));
return array;
}
第二个在方法databaseToString()中调用,我从其他地方复制,以防我的方法写错了。
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_OWES + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
//Position after the last row means the end of the results
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex(COLUMN_DESC)) != null) {
dbString += c.getString(c.getColumnIndex(COLUMN_DESC));
}
c.moveToNext();
}
db.close();
return dbString;
}
DBtoArray中的记录器都显示数据库为空。这些方法是一个接一个地调用的,如addAnOwe()方法中所示。为什么不保存数据?
答案 0 :(得分:1)
为什么不直接传递DB.addOwe(字符串描述,整数x)并在DBHelper类中接受!?您要存储字符串和整数,但是您希望将它们放入另一个要在DBHelper中检索的对象中,以使用其他方法获取对象内部参数的值。我相信直接传递值会减少很多复杂性和运行时间。 :)