Reputation: 29
hey guys i am developing a quiz where in i have 50 question stored and then i want it 10 questions only to display..the questions is randomly display..but my problem is it should be 10 questions to display in the quiz.please help me...help is really appreciated..
public class Question1 extends Activity {
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
static int index = 50;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question10);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1 * 1000);
finish();
loadQuestions();
Intent intent = new Intent(Question1.this,
Question2.class);
Question1.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList()throws JSONException{
Random rnd = new Random();
for (int i = quesList.length() - 1; i >= 0; i--)
{
int j = rnd.nextInt(i + 1);
// Simple swap
Object object = quesList.get(j);
quesList.put(j, quesList.get(i));
quesList.put(i, object);
}
return quesList;
}
Upvotes: 0
Views: 930
Reputation: 128428
As you want to have dynamic 10 questions in every quiz, you can shuffle ArrayList by using Collections.shuffle(YourList)
and take first 10 from that shuffled list.
But, as you are having JSONArray, you have to iterate it and prepare ArrayList, there way you would be able to use shuffle()
.
Refer answer of ogzd, there way you will be having questions as a List<JsonObject>
, now you just call shuffle method as i have mentioned above:
Collections.shuffle(questions);
Now, it will shuffle the questions list so you have to copy or take first 10 items from it.
Upvotes: 2
Reputation: 5692
Try:
List<JsonObject> questions = new ArrayList<JsonObject>();
int n = Math.min(10, quesList.length());
for(int i = 0; i < n; i++) {
JsonObject question = quesList.getJsonObject(i);
questions.add(question);
}
Upvotes: 0