我正在关注http://www.vogella.de/articles/AndroidSQLite/article.html教程。我现在正在尝试更改系统,因此不仅有字段“评论”,而是字段“项目”和“价格”。
现在我有2个Coloums而不是一个光标似乎导致应用程序崩溃! 例如,下面的代码如下:
public List<Item> getAllItems() {
List<Item> items = new ArrayList<Item>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Item item = cursorToItem(cursor);
items.add(item);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return items;
}
private Item cursorToItem(Cursor cursor) {
Item item = new Item();
item.setId(cursor.getLong(0));
item.setItem(cursor.getString(1));
item.setPrice(cursor.getString(2));
return item;
}
LINE:
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
allColumns, null, null, null, null, null);
导致错误的是什么,我认为这与我有一个额外的列这一事实有关。有人可以告诉我如何编辑这一行,让它工作,我已经尝试但不明白这个游标查询。
编辑:通过用null替换allcolumns,它运行了。但现在崩溃了:
public Item createItem(String item, String price) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_ITEM, item);
values.put(MySQLiteHelper.COLUMN_PRICE, price);
long insertId = database.insert(MySQLiteHelper.TABLE_ITEMS, null,
values);
// To show how to query
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
return cursorToItem(cursor);
}
在线:
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
这是MySQLHelper.js:
package nupos.nupay.app;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_ITEMS = "items";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_ITEM = "item";
public static final String COLUMN_PRICE = "price";
private static final String DATABASE_NAME = "items_test.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_ITEMS + "( " + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_ITEM
+ " text not null," + COLUMN_PRICE
+" text not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
onCreate(db);
}
}
编辑:问题是最初创建的数据库没有其中一个字段。
答案 0 :(得分:1)
恕我直言,allColumns
不符合MySQLiteHelper.TABLE_ITEMS
定义。在此处声明所有参与对象的声明和当前值。
另一种可能性 - database
对象未正确初始化,此时为空。你应该检查这种情况。