将位图图像从JSON数组转换为hashmap

时间:2015-08-06 06:54:28

标签: android bitmap

我试图将一个JSON对象数组放入一个hashmap。该对象包含base64格式的图像。我将图像转换为位图,需要使用hashmap将图像放入List视图。但是我我得到一个空指针异常

#Main Activity#

protected void onPostExecute(JSONObject json) {

         try {
                // Getting JSON Array from URL
             details = json.getJSONArray(TAG_Root);
                for(int i = 0; i < details.length(); i++){
                JSONObject c = details.getJSONObject(i);

                // Storing  JSON item in a Variable
                String branch = c.getString(TAG_Branch);
                String address = c.getString(TAG_Add);
                String uname = c.getString(TAG_User);
               String photo = c.getString(TAG_Photo);

               //decoding the base64 image to an png format

                byte[] imageAsBytes = Base64.decode(photo.getBytes(), Base64.DEFAULT);
                ImageView image = (ImageView)findViewById(R.id.imageView1);
               image.setImageBitmap(
                     BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
                );


                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_Branch, branch);
               map.put(TAG_Add, address);
               map.put(TAG_User, uname);
              oslist.add(map);

              HashMap<String, Object> map = new HashMap<String, Object>();
              map.put(TAG_Photo,image);
              oslist.add(map);

              //String.valueOf(TAG_Photo
                //,R.id.imageView1
                list=(ListView)findViewById(R.id.listView1);

                ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
                        R.layout.list_activity,
                        new String[] { TAG_Branch,TAG_Add, TAG_User }, new int[] {
                                R.id.textView1,R.id.textView2, R.id.textView3});

                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        int pos=position;
                        Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+pos).get("name"), Toast.LENGTH_SHORT).show();

                    }
                });

                }
        } catch (JSONException e) {
            e.printStackTrace();
        }

     }
}

2 个答案:

答案 0 :(得分:0)

由于地图

,您获得了空格
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TAG_Photo,image);

适配器将无法在其中找到所需的标记,因此它将提供null异常。

答案 1 :(得分:0)

如果photo的值是base64字符串内容,我认为您不需要photo.getBytes()

String photo = jsonObject.getString(TAG_Photo);
byte[] bytes = Base64.decode(photo, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);