So I’m making a quiz for android and I have a problem. I parse the questions and answers from a server in JSONArrays and get what I want. So when I start the activity the first question with its associated answers are displayed, the question in a TextView and the answers in a ListView. But here’s the problem, I want to see the next question when I select an answer, so I want to loop through the JSONObject and display a new question when the previous has been answered. Anyone have any idea how I can do that?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
listView = (ListView)findViewById(R.id.list_answers);
gametv = (TextView)findViewById(R.id.text_question);
Intent intent = getIntent();
final String gameID = intent.getStringExtra("gameID");
final int questionAmount = intent.getIntExtra("amount", 0);
final Set<String> set = new HashSet<String>();
JSONArray quiz = null;
try {
JSONObject json = new JSONObject();
json.put("gameID", gameID);
quiz = SendHttp.parseHttp(qURL, "result", json);
displayQuiz(quiz, questionAmount);
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView tv = (TextView)view.findViewById(R.id.tv_1);
String answerString = tv.getText().toString();
set.add(answerString);
Toast.makeText(Game.this, answerString, Toast.LENGTH_SHORT).show();
Log.w("svarat", set.toString());
}
});
}
private void displayQuiz(JSONArray jsona, int amount) throws JSONException {
gametv.setText(jsona.getJSONObject(0).getString("question"));
int numberOfAnswers = Integer.parseInt(jsona.getJSONObject(0).getString("n"));
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < numberOfAnswers; i++) {
String qans = jsona.getJSONObject(0).getString(String.valueOf(i+1));
JSONObject answer = new JSONObject(qans);
map.put("answerID", answer.getString("answerID"));
map.put("answer", answer.getString("answer"));
mylist.add(map);
map = new HashMap<String, String>();
}
SimpleAdapter sadapter = new SimpleAdapter(this, mylist, R.layout.quizlist, new String[] {"answerID","answer"},
new int[] {R.id.tv_1, R.id.tv_2});
listView.setAdapter(sadapter);
}
Have you tried calling notifyDataSetChanged() on your listView?
ADDITION
So if everything displays properly for the first question, here is an approach to increment on each answer click.