Hello I want to implement a simple survey. I successfully added the questions with an insert query. The Questions however get added every time when I run the application.
I tried to use "Drop table if exists" but nothing happens.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME= "Questionpool.db";
public static final String createdb = "Create table dtaquestions( questionId Integer Primary Key Autoincrement, dtaQuestion Varchar(100), dtaDepartment Varchar(100))";
public static final String dropdb = "Drop table if exists dtaquestions";
Context context;
public DatabaseHelper(Context context) {
super(context, DBNAME , null, 1);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createdb);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(dropdb);
}
And in the Survey class I have this,
myDb = new DatabaseHelper(this);
SQLiteDatabase DB2=myDb.getWritableDatabase();
insertQuestions(DB2);
final Cursor res = getAllData(DB2);
bViewAll = (Button) findViewById(R.id.bViewAll);
bViewAll.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onClick(View v) {
if(res.getCount()== 0){
tv.setText("nooo");
}else{
int counter = 0;
while(res.moveToNext()){
//show on screen
}
}
}
});
public void insertQuestions(SQLiteDatabase db){
String [] dtaQuestions = fillArray();
String [] dtaQuestionsDep = fillDepartment();
for (int i = 0 ; i < 18 ; i++ ){
ContentValues cv = new ContentValues();
cv.put("dtaQuestion", dtaQuestions[i]);
cv.put("dtaDepartment", dtaQuestionsDep[i]);
db.insert("dtaquestions", null, cv);
}
}
public Cursor getAllData(SQLiteDatabase db){
Cursor res = db.rawQuery("Select * from dtaquestions", null);
return res;
}
I have no idea why the drop query isn't working and the query keeps repeating itself.
Read de cocumentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.
When you create the helper the version is always 1.
super(context, DBNAME , null, 1);
You need to change the version. You can declare the version and then use it:
private static final int VERSION=2;
public DatabaseHelper(Context context) {
super(context, DBNAME , null,VERSION);
this.context = context;
}