未创建或识别Android SQLite表列。我错过了什么?

问题描述 投票:0回答:1

我正在建立一个sqlite数据库,用于存储有关产品的信息。什么时候将新项目添加到数据库中。我得到第一个表列的错误,说当我确信它应该在那里时,不存在这样的表列。我现在的意思是问题出在onCreate()上。我是sqlite的新手并为别人工作,请原谅我,如果我忽略了一些基本的东西。

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)
java android android-sqlite
1个回答
1
投票

我不相信您提供的代码存在任何问题。

那就是复制你的代码并在MainActivity中使用以下内容: -

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()
            );
        }
    }
}

结果如下(按预期)在日志中: -

04-20 07:21:16.291 10005-10005/? D/ITEMFROMLIST: Item Name is tjastjtjjta
        Initial Price = 0.0
        Current Price = 1372.0450878788292
        Price Change = 1372.0450878788292]n]tURL = tuarhwrqhh

The Likely Issue

因此,问题很可能是App已运行,然后进行了更改,将ProductName添加到表的定义但未删除数据库(通过卸载App,删除App的数据或在您的情况下增加数据库版本(删除表并重新创建表))。

删除数据库的原因是onCreate方法仅在创建数据库时自动运行。

增加数据库版本号会导致调用onUpgrade方法。这将删除然后重新创建表。

Another Cause

如果用于开发的设备具有工作/启用的备份管理器且应用程序的清单具有android:allowBackup="true",则可能会恢复应用程序的数据,从而有效地无法卸载应用程序或清除应用程序的数据。更改清单以使用android:allowBackup="false"可以克服此类问题。

在这种情况下,增加数据库版本也会起作用,因为它不依赖于删除数据库。而是在调用onUpgrade方法时工作,这个DROP是表,并调用onCreate方法。

  • 请注意,这确实依赖于相应编码的onUpgrade(在这个问题中)。

Additional

我还建议对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;
}
© www.soinside.com 2019 - 2024. All rights reserved.