Android游标超出界限异常

时间:2016-05-13 06:14:51

标签: java android sqlite

错误是游标索引越界异常,游标为空,什么也没有收到。

这是logcat:

FATAL EXCEPTION: main: com.example.root.notebook, PID:
    .database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
    at com.example.root.notebook.NotebookDbAdapter.cursorToNote(NotebookDbAdapter.java:101)
    at com.example.root.notebook.NotebookDbAdapter.createNote(NotebookDbAdapter.java:67)
    at com.example.root.notebook.NoteEditFragment$4.onClick(NoteEditFragment.java:160)
    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  

NotebookDbAdapter.java

 package com.example.root.notebook;

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

    import java.util.ArrayList;
    import java.util.Calendar;

    /**
     * Created by root on 28/04/2016.
     */
    public class NotebookDbAdapter {

        private static final String DATABASE_NAME="notebook.db";
        private static final int  DATABASE_VERSION=1;
        public static final String NOTE_TABLE="note";
        public static final String COLUMN_ID="_id";
        public static final String COLUMN_TITLE="title";
        public static final String COLUMN_MESSAGE="message";
        public static final String COLUMN_CATEGORY="category";
        public static final String COLUMN_DATE="date";

        public String[] allColumns={COLUMN_ID, COLUMN_TITLE, COLUMN_MESSAGE, COLUMN_CATEGORY, COLUMN_DATE};

        public static final String CREATE_TABLE_NOTE= " create table " + NOTE_TABLE + " ( "
                + COLUMN_ID +" integer primary key autoincrement, "
                +COLUMN_TITLE +" text not null, "
                +COLUMN_MESSAGE+ " text not null, "
                +COLUMN_CATEGORY+" integer not null, "
                +COLUMN_DATE+" ); ";
        private SQLiteDatabase sqlDB;
        private NotebookDbHelper notebookDbHelper;
        private Context context;
        public NotebookDbAdapter (Context ctx){
            context=ctx;
        }

        public NotebookDbAdapter open() throws android.database.SQLException{

            notebookDbHelper=new NotebookDbHelper(context);
            sqlDB=notebookDbHelper.getWritableDatabase();

            return this;

        }
        public void close(){

            notebookDbHelper.close();
        }

        public Note createNote(String title,String message,Note.Category category){

            ContentValues values=new ContentValues();
            values.put(COLUMN_TITLE,title);
            values.put(COLUMN_MESSAGE,message);
            values.put(COLUMN_CATEGORY,category.name());
            values.put(COLUMN_DATE, Calendar.getInstance().getTimeInMillis() + "");

            long insertId=sqlDB.insert(NOTE_TABLE,null,values);

            Cursor cursor=sqlDB.query(NOTE_TABLE,allColumns, COLUMN_ID  + " = " + insertId , null, null, null, null);
            cursor.moveToFirst();
            Note newNote=cursorToNote(cursor);
            cursor.close();
            return  newNote;

        }


        public long deleteNote(long idToDelete){
            return sqlDB.delete(NOTE_TABLE,COLUMN_ID +" = "+idToDelete ,null);
        }
        public long updateNote(long idToUpdate,String newTitle,String newMessage,Note.Category newCategory){
            ContentValues values=new ContentValues();
            values.put(COLUMN_TITLE,newTitle);
            values.put(COLUMN_MESSAGE,newMessage);
            values.put(COLUMN_CATEGORY,newCategory.name());
            values.put(COLUMN_DATE, Calendar.getInstance().getTimeInMillis() + "");

            return sqlDB.update(NOTE_TABLE, values ,COLUMN_ID + " = " + idToUpdate, null);

        }


        public ArrayList<Note> getAllnotes(){
            ArrayList<Note> notes=new ArrayList<Note>();
            Cursor cursor=sqlDB.query(NOTE_TABLE,allColumns, null ,null ,null ,null ,null);
            for (cursor.moveToLast();  !cursor.isBeforeFirst();  cursor.moveToPrevious()){
                Note note=cursorToNote(cursor);
                notes.add(note);
            }
            cursor.close();
            return notes;

        }
        private Note cursorToNote(Cursor cursor){
            Note newNote=new Note(cursor.getString(1),cursor.getString(2), Note.Category.valueOf(cursor.getString(3)),
                    cursor.getLong(0),cursor.getLong(4));
            return newNote;

        }
    private static class NotebookDbHelper extends SQLiteOpenHelper{


        NotebookDbHelper(Context ctx){
            super(ctx,DATABASE_NAME,null,DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(CREATE_TABLE_NOTE);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){

            Log.w(NotebookDbHelper.class.getName(),"upgrading database from version "+ newVersion+"to"+oldVersion+",which will destroy all old data");
            db.execSQL("Drop table if exist "+ NOTE_TABLE);
            onCreate(db);

        }
    }

    }

2 个答案:

答案 0 :(得分:2)

替换以下代码

        cursor.moveToFirst();
        Note newNote=cursorToNote(cursor);
        cursor.close();
        return  newNote;

使用

    if (cursor != null && cursor.moveToFirst()) {
            Note newNote=cursorToNote(cursor);
            cursor.close();
            return  newNote;
    } 
    else {
        return null;
    }

答案 1 :(得分:0)

试试这个:

  public ArrayList<Note> getAllnotes(){
        ArrayList<Note> notes=new ArrayList<Note>();
        Cursor cursor = sqlDB.rawQuery("SELECT * FROM " + NOTE_TABLE, null);
        if(cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    Note note=new Note(cursor.getString(1),cursor.getString(2), Note.Category.valueOf(cursor.getString(3)), cursor.getLong(0),cursor.getLong(4));
                    notes.add(note);
                } while (cursor.moveToNext());
            }
        }

        cursor.close();
        return notes;
    }