I am making an app in which the data is retrieved from the database.But I am getting an error which says
java.lang.IllegalStateException: Couldn't read row 6, col 6 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Kindly help me in finding out the solution as I am not able to get it. Also I am attaching the Java file.
public class QuizActivity extends AppCompatActivity {
TextView tv, tv1;
RadioGroup rg;
Button btn;
SQLiteDatabase sqldb;
Cursor c;
int score, nscore,question;
String n;
int array[]=new int[11];
private static final String x="SELECT * FROM questions";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_activity);
tv = (TextView) findViewById(R.id.textView4);
tv1 = (TextView) findViewById(R.id.textView9);
rg = (RadioGroup) findViewById(R.id.rg);
btn = (Button) findViewById(R.id.button2);
Bundle data = getIntent().getExtras();
if (data!=null){
n = data.getString("Name:");
}
openDatabase();
c = sqldb.rawQuery(x,null);
c.moveToFirst();
getQuestion();
tv1.setText("Score:0");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int res = rg.getCheckedRadioButtonId();
switch (res) {
case 0:
case 1:
case 2:
case 3:
break;
default:
Toast.makeText(getApplicationContext(), "Select atleast
anyone option!", Toast.LENGTH_LONG).show();
return;
}
if (res == Integer.parseInt(c.getString(6))) {
Toast.makeText(getApplicationContext(), "Correct answer!", Toast.LENGTH_LONG).show();
score += nscore;
tv1.setText("Score:" + nscore);
} else {
Toast.makeText(getApplicationContext(), "Incorrect answer!", Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(), "You have completed your quiz!", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), FinialActivity.class);
i.putExtra("Name:", n);
i.putExtra("Score:", score);
startActivity(i);
}
});
}
protected void openDatabase() {
sqldb = openOrCreateDatabase("Qwerty", Context.MODE_PRIVATE, null);
}
protected ArrayList<String>getQuestion() {
final String Table_name="questions";
String SelectQuery="SELECT * FROM "+Table_name;
MyHelper help = new MyHelper(getApplicationContext());
sqldb=help.getReadableDatabase();
sqldb=help.getWritableDatabase();
c=sqldb.rawQuery(SelectQuery,null);
ArrayList<String> data= new ArrayList<>();
if (c !=null){
if (c.moveToFirst()){
for (int i=0;i<c.getCount();i++){
data.add(c.getString(i));
c.moveToNext();
}
}
c.close();
}
return data;
}}
Change the code from this:
sqldb=help.getReadableDatabase();
sqldb=help.getWritableDatabase();
to:
sqldb=help.getWritableDatabase();
sqldb=help.getReadableDatabase();
Hope this will help you out.