Android SQLiteException语法错误代码1

时间:2015-05-14 14:10:08

标签: android syntax android-sqlite

我在应用程序中创建了数据库,代码提供了错误语法(代码1)表异常。我几乎阅读了关于这个例外的所有问题,做了所有的说法。但它仍然没有用。我无法找到问题所在。有没有人可以帮助我?

我的代码在这里:

public class NotesDatabaseAdapter {

    public static final String KEY_NAME = "name";
    public static final String KEY_IMAGE = "icon";
    public static final String KEY_DATE_TIME = "when";
    public static final String KEY_ROWID = "_id";
    private static final String TAG = "NotesDatabaseAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDatabase;
    private static final String DATABASE_TABLE = "downloads";

    /**
     * Khởi tạo Cơ sở dữ liệu
     */
    private static final String DATABASE_NAME = "blogradio.db";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_DOWNLOAD_TABLE = "create table "
            + DATABASE_TABLE + "(" + KEY_ROWID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
            + " TEXT NOT NULL, " + KEY_IMAGE + " TEXT NOT NULL, "
            + KEY_DATE_TIME + " TEXT NOT NULL);";

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i("", "abc " + CREATE_DOWNLOAD_TABLE);
            db.execSQL(CREATE_DOWNLOAD_TABLE);
        }

        @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 " + DATABASE_TABLE);
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx
     *            the Context within which to work
     */
    public NotesDatabaseAdapter(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 NotesDatabaseAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDatabase = 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 createNote(ItemDownload item) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, item.getName());
        initialValues.put(KEY_IMAGE, item.getIcon());
        initialValues.put(KEY_DATE_TIME, item.getWhen());
        return mDatabase.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 deleteNote(long rowId) {
        return mDatabase.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
     */
    // Lây toàn bộ các Ghi Chú để hiển thị lên Listview
    public Cursor fetchAllNotes() {

        return mDatabase.query(DATABASE_TABLE, new String[] { KEY_ROWID,
                KEY_NAME, KEY_IMAGE, KEY_DATE_TIME }, 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 fetchNote(long rowId) throws SQLException {

        Cursor mCursor =

        mDatabase.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
                KEY_NAME, KEY_IMAGE, KEY_DATE_TIME }, 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 updateNote(long rowId, ItemDownload item) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, item.getName());
        args.put(KEY_IMAGE, item.getIcon());

        args.put(KEY_DATE_TIME, item.getWhen());

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

MainActivity:

public class RequestClass extends Activity implements OnClickListener {
    Button start, stop, startActivity;
    int btnStart, btnStop;
    public static final String STATE = "start";
    private Intent intent;
    NotesDatabaseAdapter db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.request_layout);
        db = new NotesDatabaseAdapter(RequestClass.this);
        db.open();
        start = (Button) findViewById(R.id.btnStartService);
        stop = (Button) findViewById(R.id.btnStopService);
        startActivity = (Button) findViewById(R.id.btnStartActivity);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        startActivity.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btnStartService:
            intent = new Intent(this, ServiceClass.class);
            intent.putExtra(STATE, "http://media3.nhacvietplus.com.vn/Upload/CMS/Nam_2015/Thang_5/Ngay_7/Images/blog-radio389-5.jpg");
//          ItemDownload item = new ItemDownload("BLOGRADIO", "xxx", "http://media3.nhacvietplus.com.vn/Upload/CMS/Nam_2015/Thang_5/Ngay_7/Images/blog-radio389-5.jpg");
//          db.createNote(item);
//          db.close();
            startService(intent);

            break;
        case R.id.btnStopService:
            stopService(intent);
            break;
        case R.id.btnStartActivity:
            Intent i = new Intent(RequestClass.this, ResponseClass.class);
            startActivity(i);
            break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

Logcat:

05-14 14:08:41.152: E/SQLiteLog(1979): (1) near "when": syntax error
05-14 14:08:41.152: D/AndroidRuntime(1979): Shutting down VM
05-14 14:08:41.152: W/dalvikvm(1979): threadid=1: thread exiting with uncaught exception (group=0xa61fe908)
05-14 14:08:41.156: E/AndroidRuntime(1979): FATAL EXCEPTION: main
05-14 14:08:41.156: E/AndroidRuntime(1979): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.tadev.demodownloadservice/android.tadev.downloadservice.temp.RequestClass}: android.database.sqlite.SQLiteException: near "when": syntax error (code 1): , while compiling: create table downloads(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, icon TEXT NOT NULL, when TEXT NOT NULL);
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.os.Looper.loop(Looper.java:137)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at java.lang.reflect.Method.invokeNative(Native Method)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at java.lang.reflect.Method.invoke(Method.java:511)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at dalvik.system.NativeStart.main(Native Method)
05-14 14:08:41.156: E/AndroidRuntime(1979): Caused by: android.database.sqlite.SQLiteException: near "when": syntax error (code 1): , while compiling: create table downloads(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, icon TEXT NOT NULL, when TEXT NOT NULL);
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.tadev.downloadservice.temp.NotesDatabaseAdapter$DatabaseHelper.onCreate(NotesDatabaseAdapter.java:44)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.tadev.downloadservice.temp.NotesDatabaseAdapter.open(NotesDatabaseAdapter.java:79)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.tadev.downloadservice.temp.RequestClass.onCreate(RequestClass.java:23)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.Activity.performCreate(Activity.java:5104)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-14 14:08:41.156: E/AndroidRuntime(1979):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-14 14:08:41.156: E/AndroidRuntime(1979):     ... 11 more

2 个答案:

答案 0 :(得分:1)

您无法调用“WHEN”列,因为它是sqlite

中的关键字

答案 1 :(得分:1)

'when'是一个sqlite关键字。

public static final String KEY_DATE_TIME = "when";

像这样改变: -

public static final String KEY_DATE_TIME = "date_and_time";