I want to create a quiz app which contains 1 question and 4options for that I created a database from which the questions and options are fetched to 5 textviews using ListView
. I surfed many tutorials and using a page from stackoverflow created it using ArrayList
and Cursor
but i am getting a
error.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.shark.shopapp.merge.getData(merge.java:26)
at com.example.shark.shopapp.MainActivity.onCreate(MainActivity.java:68)
It is showing in a Cursor.query() line. MainActivity:
setContentView(R.layout.ques_layout); db=openOrCreateDatabase("check1.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.execSQL("CREATE TABLE que(ques TEXT,optn1 TEXT,optn2 TEXT,optn3 TEXT,optn4 TEXT)");
ListView l1=(ListView)findViewById(R.id.listView2);
merge mer=new merge(this);
ArrayList<String> data=mer.getData();
l1.setAdapter(new ArrayAdapter<String>(this,R.layout.ques_layout,data));
db.close();
Merge.java:
public merge(Context c){ourContext=c;}
public ArrayList<String> getData() {
String[] columns = new String[]{ques, optn1, optn2, optn3, optn4};
Cursor c2=db.query(DATABASE_TABLE,columns,null,null,null,null,null);
ArrayList<String> result = new ArrayList<String>();
int ques = c2.getColumnIndex("_id");
int optn1 = c2.getColumnIndex("optn1");
int optn2 = c2.getColumnIndex("optn2");
int optn3 = c2.getColumnIndex("optn3");
int optn4 = c2.getColumnIndex("optn4");
for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
result.add(c2.getString(ques) + c2.getString(optn1) + c2.getString(optn2) + c2.getString(optn3) + c2.getString(optn4));
}
db.close();
return result;
}
}
try this :
String strQuery="select option from (select option1 as option from table
union all
select option2 as option from table
union all
select option3 as option from table
union all
select option4 as option from table) as result";
Cursor c2 = db.SelectQuery(strQuery);
String[] from ={"option"};//you can add as many as you need.
in[] to to = {"R.id.TextViewID"};//you can add as many as you need.
SimpleCursorAdapter sca = new SimpleCursorAdapter(youractivityname.this,R.layout.listviewlayout,c2,from,to); yourlistview.setAdapter(sca);