我在创建数据库android时遇到了一些错误

时间:2015-07-19 12:39:37

标签: android database

我正在尝试使用this教程创建数据库。我在android开发方面还是新手,所以这可能很容易,但仍在学习。这是我得到的错误:

07-19 14:37:18.235: E/SQLiteLog(9089): (1) no such table: grocery
07-19 14:37:18.245: E/AndroidRuntime(9089): FATAL EXCEPTION: main
07-19 14:37:18.245: E/AndroidRuntime(9089): Process: com.dusandimitrijevic.grocerylist, PID: 9089
07-19 14:37:18.245: E/AndroidRuntime(9089): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dusandimitrijevic.grocerylist/com.dusandimitrijevic.grocerylist.MainActivity}: android.database.sqlite.SQLiteException: no such table: grocery (code 1): , while compiling: SELECT _id, title, price FROM grocery
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.ActivityThread.access$900(ActivityThread.java:177)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.os.Looper.loop(Looper.java:145)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.ActivityThread.main(ActivityThread.java:5942)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at java.lang.reflect.Method.invoke(Native Method)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at java.lang.reflect.Method.invoke(Method.java:372)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
07-19 14:37:18.245: E/AndroidRuntime(9089): Caused by: android.database.sqlite.SQLiteException: no such table: grocery (code 1): , while compiling: SELECT _id, title, price FROM grocery
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1440)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1287)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1158)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1326)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at com.dusandimitrijevic.data.GroceryDbAdapter.fetchAllItems(GroceryDbAdapter.java:145)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at com.dusandimitrijevic.grocerylist.MainActivity.fillData(MainActivity.java:79)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at com.dusandimitrijevic.grocerylist.MainActivity.onCreate(MainActivity.java:59)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.Activity.performCreate(Activity.java:6289)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
07-19 14:37:18.245: E/AndroidRuntime(9089):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
07-19 14:37:18.245: E/AndroidRuntime(9089):     ... 10 more

以下是数据库的代码:

package com.dusandimitrijevic.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Simple notes database access helper class. Defines the basic CRUD operations
 * for the notepad example, and gives the ability to list all notes as well as
 * retrieve or modify a specific note.
 * 
 * This has been improved from the first version of this tutorial through the
 * addition of better error handling and also using returning a Cursor instead
 * of using a collection of inner classes (which is less scalable and not
 * recommended).
 */
public class GroceryDbAdapter {

    public static final String KEY_TITLE = "title";
    public static final String KEY_PRICE = "price";
    public static final String KEY_ROWID = "_id";

    private static final String TAG = "GroceryDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private Context mCtx;

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "create table grocery (_id integer primary key autoincrement, "
        + "title text not null, price text not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "grocery";
    private static final int DATABASE_VERSION = 2;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public GroceryDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public GroceryDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new note using the title and body provided. If the note is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */
    public long createItem(String title, String price) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_PRICE, price);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteItem(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllItems() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
                KEY_PRICE}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchItem(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_TITLE, KEY_PRICE}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of note to update
     * @param title value to set note title to
     * @param body value to set note body to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateItem(long rowId, String title, String price) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_PRICE, price);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

我还在学习,所以任何帮助或建议都会被高估。

2 个答案:

答案 0 :(得分:2)

最有可能的是,您更改了 DATABASE_CREATE 字符串中定义的SQL语句,而不是更改数据库版本。

更改数据库版本,调用onUpgrade()并调用其中的SQL语句:

db.execSQL("DROP TABLE IF EXISTS notes");

这尝试删除表可能不存在。

然后调用onCreate()并尝试创建一个表,但由于它可能已经存在,所以没有任何反应,但您的表仍然是您在版本1中创建的表。

因此,解决方案可以是:

  1. 从您的设备取消安装应用程序并重新安装(将删除以前版本的数据库)

  2. 删除说明:

    db.execSQL("DROP TABLE IF EXISTS notes");
    

    并使用:

    db.execSQL("DROP TABLE IF EXISTS grocery");
    

答案 1 :(得分:-1)

在您的DATABASE_CREATE查询中删除字符串中的分号它导致错误

private static final String DATABASE_CREATE =
    "create table grocery (_id integer primary key autoincrement, "
    + "title text not null, price text not null)";//removed which was semicolon inside it