Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error - android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

I'm triying to do a database, but i have a problem...

This is the log:

E/AndroidRuntime(894): FATAL EXCEPTION: main
E/AndroidRuntime(894): java.lang.IllegalStateException: Could not execute method of the activity
E/AndroidRuntime(894):  at android.view.View$1.onClick(View.java:3044)
E/AndroidRuntime(894):  at android.view.View.performClick(View.java:3511)
E/AndroidRuntime(894):  at android.view.View$PerformClick.run(View.java:14105)
E/AndroidRuntime(894):  at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime(894):  at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(894):  at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(894):  at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime(894):  at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(894):  at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(894):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime(894):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime(894):  at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(894): Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime(894):  at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(894):  at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(894):  at android.view.View$1.onClick(View.java:3039)
E/AndroidRuntime(894):  ... 11 more
E/AndroidRuntime(894): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
E/AndroidRuntime(894):  at android.database.AbstractCursor.checkPosition(AbstractCursor.java:400)
E/AndroidRuntime(894):  at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
E/AndroidRuntime(894):  at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)
E/AndroidRuntime(894):  at and.mGroup.VirtualTrener.DatabaseControl.fetchItemByType(DatabaseControl.java:59)
E/AndroidRuntime(894):  at and.mGroup.VirtualTrener.DatabaseManageActivity.onClick(DatabaseManageActivity.java:48)
E/AndroidRuntime(894):  ... 14 more

Here is DatabaseControl.java:

public class DatabaseControl {

    private static final String KEY_ROWID = "_id";
    private static final String KEY_NAME = "NAME";
    private static final String KEY_BKI = "BKI";
    private static final String KEY_CKM = "CKM";

    private static final String DATABASE_TABLE ="inventory";

    private Context context;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;

    public DatabaseControl(Context context){
        this.context = context;
    }

    public DatabaseControl open() throws SQLiteException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        return this;
    }

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

    public long addItem(String NAME, int BKI, int CKM) {
        ContentValues setUpVals = CreateContentValues(NAME,BKI,CKM);
        return database.insert(DATABASE_TABLE, null, setUpVals);

    }



    public boolean updateItem (long id, String NAME, int BKI, int CKM){
        ContentValues updateVals = CreateContentValues(NAME,BKI,CKM);

        return database.update(DATABASE_TABLE, updateVals, KEY_ROWID + "="+ id, null) > 0;
    }


    public long fetchItemByType(String type){
        Cursor dbCursor;

        long id =0;
        try {
            dbCursor = database.query(true, DATABASE_TABLE, new String[]{KEY_ROWID},KEY_NAME + "= '" + type + "'" , null, null, null, null, null);
            dbCursor.moveToFirst();
            id = dbCursor.getLong(dbCursor.getColumnIndex(KEY_ROWID));
        } catch (SQLiteException e) {
            id = -1;
        }
        return id;      
    }

    public String fetchAllItems(){
        String allData = "";

        Cursor dbCursor;
        try {
            dbCursor = database.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_BKI, KEY_CKM}, null, null, null, null, null);
            //dbCursor.getCount();
            int iRow = dbCursor.getColumnIndex(KEY_ROWID);
            int iName = dbCursor.getColumnIndex(KEY_NAME);
            int iBKI = dbCursor.getColumnIndex(KEY_BKI);
            int iCKM = dbCursor.getColumnIndex(KEY_CKM);

            for (dbCursor.moveToFirst(); !dbCursor.isAfterLast(); dbCursor.moveToNext())
            {
                allData = allData + " " + dbCursor.getString(iRow) + "\t" + dbCursor.getString (iName) + "\t" + dbCursor.getString (iBKI) + "\t" + dbCursor.getString (iCKM) + "\n";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            allData = "";

        }
        return allData;
    }

    public boolean deleteItem(long id){
        return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + id, null) > 0;
    }

    private ContentValues CreateContentValues(String nAME, int bKI, int cKM) {
        // TODO Auto-generated method stub
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, nAME);
        values.put(KEY_BKI, bKI);
        values.put(KEY_CKM, cKM);
        return values;
    }
}

Here is DatabaseHelper.java:

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "ItemInventorydb";
    private static final int DATABASE_VERSION = 1;


    private static final String DATABASE_CREATE = "CREATE TABLE inventory (" +
    "_id integer PRIMARY KEY AUTOINCREMENT," +
            "NAME text," +
            "BKI integer," +
            "CKM integer" +
            ");";


    public 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) {
        db.execSQL("DROP TABLE IF EXIST inventory");
        onCreate(db);

    }
}

Here is DatabaseManageActivity.java:

public class DatabaseManageActivity extends Activity {

    private EditText nazwaInput;
    private EditText bkiInput;
    private EditText ckmInput;
    private DatabaseControl dbControl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wejscie_sesje);
        dbControl = new DatabaseControl(this);
        nazwaInput = (EditText) findViewById(R.id.name);
    }

    public void onClick(View arg){
        String nazwaData = nazwaInput.getText().toString().toLowerCase();
        //String bkiData = bkiInput.getText().toString();
        //String ckmData = ckmInput.getText().toString();
        Dialog notice = new Dialog(this);
        TextView msgBody = new TextView(this);
        msgBody.setTextSize(20);
        long tempVal =0;


        switch (arg.getId()){
        case R.id.addItem:

            try {
                //int bkiDataAsNum =Integer.parseInt(bkiData);
                //int ckmDataAsNum =Integer.parseInt(ckmData);
                int bkiDataAsNum = 3500;
                int ckmDataAsNum = 24;
                dbControl.open();

                if ((tempVal = dbControl.fetchItemByType(nazwaData)) != -1){
                    if(dbControl.updateItem(tempVal, nazwaData, bkiDataAsNum, ckmDataAsNum)){
                        notice.setTitle("Zaktualizowano!");
                        msgBody.setText("Item, który istniał zostal zaktualizowany");
                    }
                    else {
                        notice.setTitle("Aktualizacja zakończona niepowodzeniem");
                        msgBody.setText("Item, ktory istniał nie został zaktualizowany");
                    }
                }
                else {
                    long rowId =0;
                    rowId = dbControl.addItem(nazwaData, bkiDataAsNum, ckmDataAsNum);
                    notice.setTitle("Item umieszczony!");
                    msgBody.setText("Item umieszczony na pozycji" + rowId);
                }
                dbControl.close();
            }
            catch (SQLiteException e) {
                e.printStackTrace();
                notice.setTitle("Umieszczenie zakończone niepowodzeniem !");
                msgBody.setText("Błąd SQL");
            }
            catch (NumberFormatException e) {
                e.printStackTrace();
                notice.setTitle("Umieszczenie zakończone niepowodzeniem!");
                msgBody.setText("Wartość musi być wartością numeryczną!");
        }
        notice.setContentView(msgBody);
        notice.show();
        break;

        case R.id.updateItem:


            try{
                //int bkiDataAsNum =Integer.parseInt(bkiData);
                int bkiDataAsNum = 3500;
                int ckmDataAsNum = 24;
                //int ckmDataAsNum =Integer.parseInt(ckmData);

                dbControl.open();

                if ((tempVal = dbControl.fetchItemByType(nazwaData)) != -1){
                    if(dbControl.updateItem(tempVal, nazwaData, bkiDataAsNum, ckmDataAsNum)){
                        notice.setTitle("Zaktualizowano!");
                        msgBody.setText("Item, zostal zaktualizowany");
                    }
                    else {
                        notice.setTitle("Aktualizacja zakończona niepowodzeniem");
                        msgBody.setText("Aktualizacja zakończona niepowodzeniem, nie znaleziono rekordów");
                    }
                }
                else
                {
                    notice.setTitle("Aktualizacja zakończona niepowodzeniem");
                    msgBody.setText("Item nie został znaleziony!");
                }
                dbControl.close();


    }
            catch (SQLiteException e) {
                e.printStackTrace();
                notice.setTitle("Update zokończony niepowodzeniem!");
                msgBody.setText("Błąd SQL");
            }
            catch (NumberFormatException e) {
                e.printStackTrace();
                notice.setTitle("Update zokończony niepowodzeniem!");
                msgBody.setText("Wartość musi być wartością numeryczną!");
        }
        notice.setContentView(msgBody);
        notice.show();
        break;

        case R.id.deleteItem:

            try{

                dbControl.open();

                if ((tempVal = dbControl.fetchItemByType(nazwaData)) != -1){
                    if(dbControl.deleteItem(tempVal)){
                        notice.setTitle("Usunięto!");
                        msgBody.setText("Item, zostal usunięty");
                    }
                    else {
                        notice.setTitle("Usunięcie zakończone niepowodzeniem");
                        msgBody.setText("Usunięcie zakończone niepowodzeniem, nie znaleziono rekordów");
                    }
                }
                else
                {
                    notice.setTitle("Usunięcie zakończone niepowodzeniem");
                    msgBody.setText("Item nie został znaleziony!");
                }
                dbControl.close();


    }
            catch (SQLiteException e) {
                e.printStackTrace();
                notice.setTitle("Usunięcie zakończone niepowodzeniem!");
                msgBody.setText("Błąd SQL");
            }

        notice.setContentView(msgBody);
        notice.show();
        break;

        case R.id.viewData:
            Intent i = new Intent("android.intent.action.DatabaseViewer");
            startActivity(i);
            break;
            default:
}
    }}

and DatabaseViewer.java:

public class DatabaseViewer extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dataview);
        TextView content = (TextView) findViewById(R.id.dataOutput);
        DatabaseControl control = new DatabaseControl(this);
        String result = "_id\t NAME\t BKI\t CKM \n ";

        try {
            control.open();
            result = result + ""+ control.fetchAllItems();
            control.close();
        }
        catch (SQLiteException e) {
            e.printStackTrace();
        }
        content.setText(result);
    }

}

I have not idea what is wrong... Could You help me? It will be nice , when if You will answering, You will using simple to understand language.

like image 683
Krystian Bersztolc Avatar asked May 13 '12 18:05

Krystian Bersztolc


1 Answers

In fetchItemByType check if cursor.moveToFirst() returns true if not then you dont have any data and you can return -1. I think CursorIndexOutOfBoundsException is not getting caught in your program and 0 is getting returned from the fetchItemByType function.

like image 122
Tarun Avatar answered Nov 14 '22 23:11

Tarun