如何在android中使用json数组限制问题的长度?

时间:2013-02-22 07:21:32

标签: java android limit

嘿家伙我正在开发一个测验,其中我有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;


}

2 个答案:

答案 0 :(得分:2)

由于您希望在每个测验中都有动态的10个问题,您可以使用Collections.shuffle(YourList)对ArrayList进行混洗,并从该混洗列表中取10个。

但是,当您拥有JSONArray时,您必须迭代它并准备ArrayList,这样您就可以使用shuffle()

更新

请参阅ogzd的回答,您将有问题作为List<JsonObject>,现在您只需调用shuffle方法,如上所述:

Collections.shuffle(questions);

现在,它将随机播放问题列表,因此您必须复制或从中获取前10个项目。

答案 1 :(得分:0)

尝试:

 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);
 }