lundi 14 décembre 2015

how to add new rows on top after clearing rows in Android SQLite

OK.there is the code for my class which exstends SQLiteOpenHelper.what this database keeps is not interesting. the questions is: for example I entere 10 rows in the table. after deleting all rows with the method

 public void removeQuestion(int id){
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(TABLE_NAME, COL_ID + "=" + id, null);
        }

the database is cleared and I add new Row. the problem is that the ID of row is 11,not 1.( as the table is cleaned,new row must be first row in the table).How can I control this? this is the code:

public String ID = "id";
public String QUESTION = "question";
public string ANSWER = "answer ;     
public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,QUESTION TEXT,ANSWER TEXT)");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
        public void addQuestion(Question question){
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(COL_QUESTION, question.QUESTION);
            values.put(COL_V1, question.V1);
            values.put(ANSWER,question.ANSWER);
            // Inserting Row
            db.insert(TABLE_NAME, null, values);
            db.close(); // Closing database connection
        }
        public ArrayList<Question> getAllQuestions(){
            ArrayList<Question> questions = new ArrayList<Question>();
            String selectQuery = "SELECT  * FROM " + TABLE_NAME;
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            if (cursor.moveToFirst()) {
                do {
                    Question question = new Question();
                    question.ID = Integer.parseInt(cursor.getString(0));
                    question.QUESTION= cursor.getString(1);                
                    question.ANSWER=cursor.getString(2);
                    questions.add(question);
                } while (cursor.moveToNext());
            }
            cursor.close();
            db.close();
            return questions;
        }
        public void removeQuestion(int id){
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(TABLE_NAME, COL_ID + "=" + id, null);
        }

Aucun commentaire:

Enregistrer un commentaire