[英]how to limit the length of the questions using json array in android?
嘿家伙我正在開發一個測驗,在我有50個問題存儲,然后我想要10個問題只顯示..問題是隨機顯示..但我的問題是它應該是10個問題,以顯示在測驗。請幫助我...幫助真的很感激..
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;
}
由於您希望在每個測驗中都有動態10個問題,您可以使用Collections.shuffle(YourList)
ArrayList進行混洗,並從該混洗列表中取10個問題。
但是,當您擁有JSONArray時,您必須迭代它並准備ArrayList,這樣您就可以使用shuffle()
。
請參閱ogzd的答案,還有你將有問題的一種方式List<JsonObject>
現在你只需要調用洗牌方法,我所提到的:
Collections.shuffle(questions);
現在,它將隨機播放問題列表,因此您必須復制或從中獲取前10個項目。
嘗試:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.