如何正确迭代hashmap元素的arraylist

时间:2015-01-15 05:28:32

标签: java android json

我正在从资产文件夹中读取本地JSON Feed。我的json数组中有两个对象。我已成功读取,然后将数据作为键/值对放入List中。我已迭代列表,并希望在TextView中显示数据。我的Android活动代码为

package com.aquib.quizapp;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

public class QuizActivity extends Activity {

    TextView questionName;
    RadioButton option1, option2, option3, option4;
    Button nextQuestion;
    String questionValue, option1Value, option2Value, option3Value,
            option4Value;
    int questionNumber = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        questionName = (TextView) findViewById(R.id.qestionName);
        option1 = (RadioButton) findViewById(R.id.option1);
        option2 = (RadioButton) findViewById(R.id.option2);
        option3 = (RadioButton) findViewById(R.id.option3);
        option4 = (RadioButton) findViewById(R.id.option4);
        nextQuestion = (Button) findViewById(R.id.next_question);

        try {
            readJSON();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        setView(questionNumber, questionValue, option1Value, option2Value,
                option3Value, option4Value);

        if (questionNumber < 3) {
            nextQuestion.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    setView(questionNumber, questionValue, option1Value,
                            option2Value, option3Value, option4Value);
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.quiz, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public String loadJSONFromAsset() {
        String data = null;
        try {

            InputStream is = getAssets().open("quiz.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            data = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return data;
    }

    public void readJSON() throws JSONException {

        JSONObject object = new JSONObject(loadJSONFromAsset());
        JSONArray jArray = object.getJSONArray("quiz");
        List<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li = null;

        for (int i = 0; i < jArray.length(); i++) {

            JSONObject data = jArray.getJSONObject(i);

            int questionNumberValue = data.getInt("question_number");
            String queNumber = String.valueOf(questionNumberValue);
            String questionValue = data.getString("question");
            String option1Value = data.getString("option1");
            String option2Value = data.getString("option2");
            String option3Value = data.getString("option3");
            String option4Value = data.getString("option4");

            Log.d("Details-->", questionValue);
            Log.d("Question Number", queNumber);

            // Add your values in your `ArrayList` as below:

            m_li = new HashMap<String, String>();
            m_li.put("question_number", queNumber);
            m_li.put("question", questionValue);
            m_li.put("option1", option1Value);
            m_li.put("option2", option2Value);
            m_li.put("option3", option3Value);
            m_li.put("option4", option4Value);

            formList.add(m_li);
        }

        Iterator<HashMap<String, String>> itr = formList.iterator();
        while (itr.hasNext()) {
            HashMap<String, String> map = (HashMap<String, String>) itr.next();
            questionNumber = Integer.parseInt(map.get("question_number"));
            questionValue = map.get("question");
            option1Value = map.get("option1");
            option2Value = map.get("option2");
            option3Value = map.get("option3");
            option4Value = map.get("option4");
            Log.d("Question Number", String.valueOf(questionNumber));
            Log.d("Question Name", questionValue);
            Log.d("Option 1", option1Value);
            Log.d("Option 2", option2Value);
            Log.d("Option 3", option3Value);
            Log.d("Option 4", option4Value);

        }

    }

    private void setView(int questionNumber, String questionValue,
            String option1Value, String option2Value, String option3Value,
            String option4Value) {

        questionName.setText("Q." + String.valueOf(questionNumber)
                + questionValue);
        option1.setText(option1Value);
        option2.setText(option2Value);
        option3.setText(option3Value);
        option4.setText(option4Value);
        questionNumber++;
    }
}

我的json文件是

{
    "quiz": [
    {
      "question_number" : 0,
      "question": "What is capital of India?",
      "option1": "New Delhi",
      "option2": "Agra",
      "option3": "Noida",
      "option4": "Jaipur"
    },

    {
      "question_number" : 1,
      "question": "What is capital of Rajasthan?",
      "option1": "Agra",
      "option2": "New Delhi",
      "option3": "Lucknow",
      "option4": "Noida"
    }
  ]
}

我在Logcat中得到了正确的结果。但我不知道为什么第二个json数据首先显示,甚至我的按钮不工作而不显示其他数据。请帮忙。

3 个答案:

答案 0 :(得分:1)

你可以用这种方式将值放在hashmap中

for (int i = 0; i < jArray.length(); i++) {

            JSONObject data = jArray.getJSONObject(i);

            int questionNumberValue = data.getInt("question_number");
            String queNumber = String.valueOf(questionNumberValue);
            String questionValue = data.getString("question");
            String option1Value = data.getString("option1");
            String option2Value = data.getString("option2");
            String option3Value = data.getString("option3");
            String option4Value = data.getString("option4");

            Log.d("Details-->", questionValue);
            Log.d("Question Number", queNumber);

            // Add your values in your `ArrayList` as below:

            m_li = new HashMap<String, String>();
            m_li.put("question_number"+i, queNumber);
            m_li.put("question"+i, questionValue);
            m_li.put("option1"+i, option1Value);
            m_li.put("option2"+i, option2Value);
            m_li.put("option3"+i, option3Value);
            m_li.put("option4"+i, option4Value);

            formList.add(m_li);
        }

和使用for循环相同的u将从hashmap获取值..

从hashmap获取值..

      Iterator myVeryOwnIterator = meMap.keySet().iterator();  
while(myVeryOwnIterator.hasNext()) { 
    String key=(String)myVeryOwnIterator.next();
     String value=(String)meMap.get(key);
     Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show(); 
    }

答案 1 :(得分:0)

最简单的方法是迭代ArrayList中的所有HashMaps,然后迭代Map中的所有键:

for (HashMap<String, String> map : formList)
     for (Entry<String, String> entry : map.entrySet())
         view.append(entry.getKey() + " => " + entry.getValue());

答案 2 :(得分:0)

首先使用QUIZ的POJO类而不是使用hashMap,然后将POJO类插入到arraylist中。 为了传递您的JSON数据,您还可以使用GSON库。