我应该如何使用ArrayList <hashmap <string,string =“”>&gt;用于添加文本数据以及图像?

时间:2016-09-03 06:31:29

标签: java android arraylist hashmap

我应该如何使用ArrayList&gt;用于添加文本数据和图像?

//first activity
persons = new HashMap<String,String>();
                    persons.put("teacher_name", TEACHER_NAME);//TEACHER_NAME is JSON response
                    persons.put("course_name", COURSE_NAME);//COURSE_NAME JSON response
                    persons.put("subject_name", SUBJECT_NAME);//SUBJECT_NAME JSON response
                    persons.put("profileimage", PROFILE_IMAGE);//PROFILE_IMAGE JSON response
                    personList.add(persons); //personList is an arrayList
i.putExtra("teachersAL", personList); // Intent to another activity

//Second class

teachername = getIntent().getStringExtra("teacher_name");
                coursename = getIntent().getStringExtra("course_name");
                subjectname = getIntent().getStringExtra("subject_name");
                profileimage = getIntent().getStringExtra("profileimage");

adapter = new SimpleAdapter(//MainHome is Second class's name
                        MainHome.this, personList, R.layout.mainhome,
                        new String[]{teachername,coursename,subjectname,profileimage},
                        new int[]{R.id.teachername, R.id.coursename, R.id.subjectname, R.id.profileimage}
                );
                list.setAdapter(adapter);

这里我收到了图片的网址,但是我想将图片和其他数据一起添加到我的Arraylist中,以便我可以使用SimpleAdapter轻松地将其传递给视图。

我怎样才能做到这一点?
我做对了还是应该选择其他方式?

2 个答案:

答案 0 :(得分:0)

您需要将位图编码为Base64字符串 以下是编码代码:

您可以使用 Base64 类来执行此操作,

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT); // Add this string to your HasMap.

但是,你需要使用bytearray,

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray(); 

您可以使用其他一些内置方法来使用Base64。

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

快乐的编码!!

答案 1 :(得分:0)

您可以将图片的链接存储在HashMap中:

list.add(new HashMap("imageUrl"," your image url"));

不建议将图像转换为ByteArray并将其存储为图像,因为它需要大量内存和处理。

如果图片位于某个服务器上,您可以使用GlidePicasso轻松将其加载到您的应用中,例如:

Glide.with(this).load(imageUrl).into(yourImageView);
Picasso.with(this).load(imageUrl).into(yourImageView);

或者,如果您的SD卡中有图像,那么您可以定位特定的文件夹,如:

File imgFile = new  File(imageUrl);

if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}