Android项目-保存JSON数组到HashMap和检索Map值



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

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

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

更重要的是,在getBottles()中,我需要知道如何设置0。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;
            }
    }
}

我想我不完全理解你的问题,但是如果你把每个瓶子hashmap添加到数组列表(顺便说一下,我看到你有一个arraylist 在我看来,它的目的应该是什么呢?

你可以,然后,循环你的数组列表包含你的hashmap: arrayListOfBottles.get(position)

最新更新