Search code examples
androidcursorandroid-sqlite

Load database column with query result not working


I'm trying to load a database column with a cursor result for my quiz app. The reason for this is that i want to populate a list view with the questions in a each category so i set up this:

public void putValues(){
    for (int i = 0; i < 18; i++) {
        Cursor contentCursor = null;
        contentCursor = mDB
                .rawQuery("select count(*) from questions_en where used = 0 and category" + " = " + i, null);

        if(contentCursor.getCount() >0 )
            contentCursor.moveToFirst();

        if (contentCursor.isAfterLast()) {
            contentCursor.close();
            mDB.close();
            return;
        }
        int contentCursorInt = contentCursor.getInt(0);
        Cursor upateCursor = null;
        upateCursor = mDB.rawQuery("update categories_en set questions_count" + " = " + contentCursorInt + " where " + "_id" + " = " + i, null);
        upateCursor.moveToNext();
        upateCursor.close();
        contentCursor.close();
    }

}

so that when the user clicks an answer (on the question screen) used becomes 1(or any non-zero value) the query result changes. The above code works fine the very first time. Because i haven't set up the question screen, i added this query:

public void test(){
    Cursor cus = mDB.rawQuery("update questions_en set used = 1 where category = 2 and _id = 146", null); 
    cus.close();
}

to my DB Adapter and then called this method from my MainActivty

        @Override
        public void onClick(View v) {
            TestAdapter mTest = new TestAdapter(MainActivity.this);
            mTest.createDatabase();
            mTest.open(); 
            mTest.test();
            Log.d(DBHelper.TAG, " Worked ");
            mTest.close();

        }
    });

But when i click on this and go to my ListActivity I expected the value of category 2 to have changed since the query had just been carried out again. But it doesn't reduce. I pulled out my DB from DDMS(file explorer) and i found out that the query to _id = 146 actually didn't change used to 1. Any help on what may be the cause?


Solution

  • Solve the problem with the help of this.

    I just changed this:

    public void test(){
        Cursor cus = mDB.rawQuery("update questions_en set used = 1 where category = 2 and _id = 146", null); 
        cus.close();
    }
    

    to this

    public void test(){
            int id = 3;
            ContentValues data = new ContentValues();
            data.put(DBHelper.KEY_USED, "1");
            mDB.update(DBHelper.KEY_QUESTIONS_TABLE, data, DBHelper.KEY_ID + " = " + id , null);
    }