繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM