每次用户在android中使用json数组播放时,如何在测验中随机化问题

时间:2013-02-22 04:00:46

标签: java javascript android json random

我开发了一个简单的小测验,其中我存储了50个问题。我的问题是,我无法随机化问题,每次用户都应该随机播放,只显示10个问题...请帮助我。使用这个An efficient way to shuffle a JSON array in java?完成..但它不起作用!!!!!非常感谢你的帮助!

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 shuffleJsonArray (JSONArray quesList) throws JSONException {
    // Implementing Fisher–Yates shuffle
        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;
}

1 个答案:

答案 0 :(得分:0)

你可以开始一个循环,随机生成问题并将它们保存在一个数组中然后使用该数组来绑定或显示问题......这将是随机的......