Java 未创建或识别Android SQLite表列。我错过了什么?
我正在建立一个sqlite数据库,它将存储有关产品的信息。将新项目添加到数据库时。当我确信第一个表列应该存在时,第一个表列出现错误,表示不存在这样的表列。我目前的想法是,问题在于onCreate。我是sqlite的新手,正在为其他人做这件事,如果我忽略了一些基本的东西,请原谅Java 未创建或识别Android SQLite表列。我错过了什么?,java,android,android-sqlite,Java,Android,Android Sqlite,我正在建立一个sqlite数据库,它将存储有关产品的信息。将新项目添加到数据库时。当我确信第一个表列应该存在时,第一个表列出现错误,表示不存在这样的表列。我目前的想法是,问题在于onCreate。我是sqlite的新手,正在为其他人做这件事,如果我忽略了一些基本的东西,请原谅 public class itemDB extends SQLiteOpenHelper { /**Information*/ private static final int DATABASE_VERSI
public class itemDB extends SQLiteOpenHelper {
/**Information*/
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ProductInfoDB";
private static final String TABLE_NAME = "ProductInfo_Table";
public static final String COL_PRODUCTNAME = "ProductName";
public static final String COL_INITIALPRICE = "InitialPrice";
public static final String COL_CURRENTPRICE = "CurrentPrice";
public static final String COL_PRICECHANGE = "PriceChange";
public static final String COL_ITEMWEBPAGE = "ItemWebPage";
/** Constructor */
public itemDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**Creates the table
* @param db Takes the database and creates a table on it
* */
@Override
public void onCreate(SQLiteDatabase db) {
String table =("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "( "
+ COL_PRODUCTNAME + " TEXT PRIMARY KEY,"
+ COL_INITIALPRICE + " REAL,"
+ COL_CURRENTPRICE + " REAL,"
+ COL_PRICECHANGE + " REAL,"
+ COL_ITEMWEBPAGE + " TEXT " + ") ");
db.execSQL(table);
}
/**needed for database
* Checks if table exists or not
* */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
/** This method adds items to the table of the database
* @param item, takes an item and gets its info, then places it on the table of the database
* */
public void addItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_PRODUCTNAME,item.getName());
contentValues.put(COL_INITIALPRICE,item.getPriceInitial());
contentValues.put(COL_CURRENTPRICE,item.getPriceCurrent());
contentValues.put(COL_PRICECHANGE,item.getPriceChange());
contentValues.put(COL_ITEMWEBPAGE,item.getUrl());
db.insert(TABLE_NAME,null ,contentValues);
db.close();
}
/** Methods aids in updating items on database
* */
public void updateItem(String oldName, Item item){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_PRODUCTNAME,item.getName());
values.put(COL_INITIALPRICE,item.getPriceInitial());
values.put(COL_CURRENTPRICE,item.getPriceCurrent());
values.put(COL_PRICECHANGE,item.getPriceChange());
values.put(COL_ITEMWEBPAGE,item.getUrl());
db.update(TABLE_NAME, values, COL_PRODUCTNAME + " = ?", new String[]{oldName});
db.close();
}
/** This method returns all the items found on the table of the database,
* recurses the table and returns a list of items
* */
public List<Item> getAllItems() {
List<Item> items = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
String itemName = cursor.getString(0);
double initialP = cursor.getDouble( 1);
double currentP = cursor.getDouble(2);
double priceC = cursor.getDouble(3);
String itemUrl = cursor.getString(4);
Item holder = new Item(itemName, initialP, currentP, priceC, itemUrl);
items.add(holder);
} while (cursor.moveToNext());
}
}
return items;
}
}
以下是我得到的错误
2019-04-19 14:14:55.490 11936-11936/edu.package E/SQLiteLog: (1) table ProductInfo_Table has no column named ProductName
2019-04-19 14:14:55.500 11936-11936/edu.packageE/SQLiteDatabase: Error inserting ProductName=tjastjtjjta PriceChange=0.0 CurrentPrice=1372.0450878788292 InitialPrice=1372.0450878788292 ItemWebPage=tuarhwrqhh
android.database.sqlite.SQLiteException: table ProductInfo_Table has no column named ProductName (code 1): , while compiling: INSERT INTO ProductInfo_Table(ProductName,PriceChange,CurrentPrice,InitialPrice,ItemWebPage) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:895)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:506)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:726)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1580)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1453)
at edu.utep.cs.cs4330.homework3.itemDB.addItem(itemDB.java:68)
at edu.utep.cs.cs4330.homework3.MainActivity.addItem(MainActivity.java:262)
at edu.utep.cs.cs4330.homework3.EntryDialog$1.onClick(EntryDialog.java:66)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:164)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6313)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
我认为您提供的代码没有任何问题 即复制代码并在Main活动中使用以下内容:-
public class MainActivity extends AppCompatActivity {
itemDB ItemDBHlpr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemDBHlpr = new itemDB(this);
Item myItem = new Item("tjastjtjjta",0.0,1372.0450878788292,1372.0450878788292,"tuarhwrqhh");
ItemDBHlpr.addItem(myItem);
List<Item> myItemList = ItemDBHlpr.getAllItems();
for (Item i: myItemList) {
Log.d("ITEMFROMLIST",
"Item Name is " + i.getName() +
"\n\tInitial Price = " + String.valueOf(i.getPriceInitial()) +
"\n\tCurrent Price = " + String.valueOf(i.getPriceCurrent()) +
"\n\tPrice Change = " + String.valueOf(i.getPriceChange()) +
"]n]tURL = " + i.getUrl()
);
}
}
}
可能的问题
因此,问题很可能是应用程序已运行,然后进行了更改,将ProductName添加到表的定义中,但数据库未被删除。通过卸载应用程序、删除应用程序的数据或(在您的情况下)增加数据库版本,会删除表并重新创建表
删除数据库之所以有效,是因为onCreate方法仅在创建数据库时自动运行
增加数据库版本号会导致调用onUpgrade方法。这将删除并重新创建表
另一个原因
如果用于开发的设备有一个工作/启用的备份管理器,并且应用程序的清单有android:allowBackup=true,则有可能恢复应用程序的数据,从而有效地取消卸载应用程序或清除应用程序的数据。将清单更改为使用android:allowBackup=false可以克服这些问题
在这种情况下,增加数据库版本也会起作用,因为它不依赖于要删除的数据库。相反,它在调用onUpgrade方法时起作用,这个DROP是表,而调用onCreate方法
注:这取决于在本问题中相应编码的onUpgrade。
附加的
我还建议对getAllItems方法进行一些修改,注释解释如下:-
/** This method returns all the items found on the table of the database,
* recurses the table and returns a list of items
* */
public List<Item> getAllItems() {
List<Item> items = new ArrayList<>();
//String selectQuery = "SELECT * FROM " + TABLE_NAME; //<<<<<<<<<< COMMENTED OUT not needed as query method builds the SQL
SQLiteDatabase db = this.getReadableDatabase();
//Cursor cursor = db.rawQuery(selectQuery, null);
// Generally recommended to use the query Convenience method rate than rawQuery
Cursor cursor = db.query(TABLE_NAME,null,null,null,null,null,null);
// No Need to do multiple checks for the same i.e. moveTo will return false if the move cannot be made
// if no rows then moveToNext returns false so loop ended
// if at last row then moveToNext will return false thus loop ended
while (cursor.moveToNext()) {
// Rather than hard coding offsets (which could change over time)
// better to get the offset according to the column name
String itemName = cursor.getString(cursor.getColumnIndex(COL_PRODUCTNAME));
double initialP = cursor.getDouble( cursor.getColumnIndex(COL_INITIALPRICE));
double currentP = cursor.getDouble(cursor.getColumnIndex(COL_CURRENTPRICE));
double priceC = cursor.getDouble(cursor.getColumnIndex(COL_PRICECHANGE));
String itemUrl = cursor.getString(cursor.getColumnIndex(COL_ITEMWEBPAGE));
//Item holder = new Item(itemName, initialP, currentP, priceC, itemUrl); // No need for intermediate Item
items.add(new Item(itemName, initialP, currentP, priceC, itemUrl)); //<<<<<<<<<< CHANGED
}
return items;
}
您可能更改了列的名称。从设备上卸载应用程序,然后重新运行以重新创建表。@对于PAS,仍然会出现相同的错误。是否可以尝试增加数据库版本以查看是否有帮助?请检查清单。你有这个属性吗:android:allowBackup=true?@forpas是的,它已经存在了。很好的解释,迈克!我在想这样的事情。我认为AndroidManifest.xml中的allowBackup=true实际上是造成问题的原因。旧的数据库文件没有被删除。@ReazMurshed我从来没有遇到过这个问题,总是使用默认值true,但我通常只使用模拟器。现在看看这方面。
/** This method returns all the items found on the table of the database,
* recurses the table and returns a list of items
* */
public List<Item> getAllItems() {
List<Item> items = new ArrayList<>();
//String selectQuery = "SELECT * FROM " + TABLE_NAME; //<<<<<<<<<< COMMENTED OUT not needed as query method builds the SQL
SQLiteDatabase db = this.getReadableDatabase();
//Cursor cursor = db.rawQuery(selectQuery, null);
// Generally recommended to use the query Convenience method rate than rawQuery
Cursor cursor = db.query(TABLE_NAME,null,null,null,null,null,null);
// No Need to do multiple checks for the same i.e. moveTo will return false if the move cannot be made
// if no rows then moveToNext returns false so loop ended
// if at last row then moveToNext will return false thus loop ended
while (cursor.moveToNext()) {
// Rather than hard coding offsets (which could change over time)
// better to get the offset according to the column name
String itemName = cursor.getString(cursor.getColumnIndex(COL_PRODUCTNAME));
double initialP = cursor.getDouble( cursor.getColumnIndex(COL_INITIALPRICE));
double currentP = cursor.getDouble(cursor.getColumnIndex(COL_CURRENTPRICE));
double priceC = cursor.getDouble(cursor.getColumnIndex(COL_PRICECHANGE));
String itemUrl = cursor.getString(cursor.getColumnIndex(COL_ITEMWEBPAGE));
//Item holder = new Item(itemName, initialP, currentP, priceC, itemUrl); // No need for intermediate Item
items.add(new Item(itemName, initialP, currentP, priceC, itemUrl)); //<<<<<<<<<< CHANGED
}
return items;
}