【问题标题】:Android Project - Saving JSON array to HashMap and Retrieving Map ValuesAndroid 项目 - 将 JSON 数组保存到 HashMap 并检索地图值
【发布时间】:2012-01-02 14:24:53
【问题描述】:

我完全是 HashMaps 的菜鸟,并且花了一周的大部分时间试图找到我需要的东西。

我成功解析了来自 HTTP 请求的 JSON 响应。我遇到的麻烦是将每个 JSON 行中的每个数据变量/值保存到 HashMap 中,然后稍后检索这些数据值。

在我解析 JSON 响应的 for 循环中,我需要确保对 put 命令使用正确的语法。

更重要的是,在 getBottles() 中,我需要知道如何将 o1.setname_abbr 设置为名称的 HashMap 中的第一条记录。我最终需要将其转换为一个 for 循环并从 JSON 响应中分配所有名称,然后从 getBottles() 中的 HashMap 中将它们全部取回。

非常感谢您的帮助!

这是我的代码...

    public class Bottles extends ListActivity {
        private int category_id;
        private int subcategory_id;
        String subcategory_idString = "false";
        String postQuery;
        private int bottleID;
        String name_abbr;
        String name_abbrArray[];
        String bottlePicture;
        private ProgressDialog m_ProgressDialog = null;
        private ArrayList<Bottles> m_bottles = null;
        private BottleAdapter m_adapter;
        private Runnable viewBottles;
        ArrayList<HashMap<String, String>> bottleNameArray = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> bottleNamesMap = new HashMap<String, String>();
        String name[];

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.bottleslist);

            String result = "";
            Bundle extras = getIntent().getExtras();
            if(extras != null){
                category_id = getIntent().getExtras().getInt("id");
                subcategory_id = getIntent().getExtras().getInt("subid");
                if(subcategory_id==0){
                    subcategory_idString = "";
                }
            }

            InputStream is = null;
            //http post
            try{
                if(subcategory_idString==""){
                    postQuery = "my api call goes here";
                }
                if(subcategory_idString=="false"){
                    postQuery = "different api call goes here";
                }
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(postQuery);
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
            }

          //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
            }

            try {
                JSONObject row = new JSONObject(result);
                JSONArray array = row.getJSONArray("response name");
                for (int i = 0; i < array.length(); i++) {
                    row = array.getJSONObject(i);
                    bottleID = row.getInt("id");
                    name_abbr = row.getString("name_abbr");
                    bottleNamesMap = new HashMap<String, String>();
                    bottleNamesMap.put("name", name_abbr);
                    bottlePicture = row.getString("bottlePicture");
                }
                }catch(Exception e){
                    Log.e("log_tag", "Error parsing JSON "+e.toString());
                }

            m_bottles = new ArrayList<Bottles>();
            this.m_adapter = new BottleAdapter(this, R.layout.bottlelistimagelayout, m_bottles);
                    setListAdapter(this.m_adapter);

            viewBottles = new Runnable(){
                public void run() {
                    getBottles();
                }
            };
        Thread thread =  new Thread(null, viewBottles, "MagentoBackground");
            thread.start();
            m_ProgressDialog = ProgressDialog.show(Bottles.this,    
                  "Please wait...", "Retrieving data ...", true);
        }
        public class Bottle{
            public String name_abbrArray;
            //public String lastName;
            //public int age;
        }
        private void getBottles(){
            try{
                //will put this into a for loop after I figure out how to reference the HashMap values
                m_bottles = new ArrayList<Bottles>();
                Bottles o1 = new Bottles();
        o1.setname_abbr("I want to get the HashMap value of the first name here");
                o1.setbottlePicture("Pending");
                Bottles o2 = new Bottles();
                o2.setname_abbr("I want to get the HashMap value of the second name here");
                o2.setbottlePicture("Completed");
                m_bottles.add(o1);
                m_bottles.add(o2);
                   Thread.sleep(2000);
                Log.i("ARRAY", ""+ m_bottles.size());
              } catch (Exception e) {
                Log.e("BACKGROUND_PROC", e.getMessage());
              }
              runOnUiThread(returnRes);
          }

        private Runnable returnRes = new Runnable() {

        public void run() {
            if(m_bottles != null && m_bottles.size() > 0){
                m_adapter.notifyDataSetChanged();
                for(int i=0;i<m_bottles.size();i++)
                m_adapter.add(m_bottles.get(i));
            }
            m_ProgressDialog.dismiss();
            m_adapter.notifyDataSetChanged();
            }
          };

        private class BottleAdapter extends ArrayAdapter<Bottles> {

            private ArrayList<Bottles> items;

            public BottleAdapter(Context context, int textViewResourceId, ArrayList<Bottles> items) {
                    super(context, textViewResourceId, items);
                    this.items = items;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                    View v = convertView;
                    if (v == null) {
                        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(R.layout.bottlelistimagelayout, null);
                    }
                    Bottles o = items.get(position);
                    if (o != null) {
                            TextView tt = (TextView) v.findViewById(R.id.toptext);
                            TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                            if (tt != null) {
                                  tt.setText("Name: "+o.getname_abbr());                            }
                            if(bt != null){
                                  bt.setText("Picture: "+ o.getbottlePicture());
                            }
                    }
                    return v;
            }
    }

}

【问题讨论】:

    标签: android arrays json hashmap


    【解决方案1】:

    我想我不完全理解你的问题,但是如果你将每个瓶子哈希图添加到一个数组列表中(顺便说一下,我看到你有一个 ArrayList 它的目的应该是什么,在我看来是空的)。

    然后,您可以循环包含哈希图的数组列表:arrayListOfBottles.get(position)

    【讨论】:

    • 谢谢 - 我越来越近了,但还没有到。我添加了 bottleNameArray.add(bottleNamesMap);因为你是对的,所以数组列表是空的。我现在可以引用bottleNameArray.get(0) 并获得像{name=sample bottle name} 这样的第一个瓶子名称。我试图将其引用为 bottleNamesMap.get(0) 但这不起作用。还尝试了 bottleNamesMap.get(name[0]) 但它不喜欢那种语法。我只需要获取位置 i 中名称的实际值(在本例中为 (0))。想法?
    • 这样做:bottleNamesMap.get(position).getString("name") 这样你应该得到“样品瓶名称”
    • 我不得不把它拆开一点,但你的建议直接让我找到了我需要的东西——谢谢你的帮助!!
    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多