
BaseAdapter,这篇博客讲深入一些,实现从本地的JSON文件读取数据
前言:前面的一篇博客讲解了怎样使用BaseAdapter,这篇博客讲深入一些,实现从本地的JSON文件读取数据,加载到listView中显示。
先看效果:
再说一下,这篇文章的功能是:在派生自BaseAdapter基础上,从本地JSON文件中读取信息,动态生成listView页面!
这篇文章的XML布局文件没有变,为了大家方便还是贴一下吧。
[html] view plain copy
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android=""
- android:orientation="horizontal" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-
- <ImageView android:id="@+id/img"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="5px"/>
-
- <LinearLayout android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
-
- <TextView android:id="@+id/name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textColor="#FFFFFF00"
- android:textSize="22px" />
- <TextView android:id="@+id/info"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textColor="#FF00FFFF"
- android:textSize="13px" />
- </LinearLayout>
-
- </LinearLayout>
一、JOSN文件内容(my_):
[html] view plain copy
- [{"name":"林珊","info":"上传了一张新照片油画”","photo":"youhua"},
- {"name":"叶亚楠","info":"上传了一张新照片日系妆”","photo":"rixizhuang"},
- {"name":"王颖","info":"上传了一张新照片最爱”","photo":"zuiai"},
- {"name":"罗智宜","info":"上传了一张新照片猫猫”","photo":"maomao"},
- {"name":"罗智宜","info":"上传了一张新照片鱼”","photo":"yu"},
- {"name":"罗智宜","info":"上传了一张新照片卖萌”","photo":"maimeng"},
- {"name":"程璐春","info":"上传了一张新照片西藏”","photo":"xizang"},
- {"name":"谢以荷","info":"上传了一张新照片海边”","photo":"haibian"}]
注意:最后的photo字段存储的JPG文件的文件名,所有的文件存放在assets/home/目录下
二、JSON数据解析方法
[java] view plain copy
- private List<Map<String, Object>> getData() {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- Map<String, Object> map = new HashMap<String, Object>();
- InputStream inputStream;
- try {
- inputStreamAssets().open("my_");
- String json=readTextFile(inputStream);
- JSONArray array = new JSONArray(json);
- for (int i = 0; i < array.length(); i++) {
- map = new HashMap<String, Object>();
- map.put("name", JSONObject(i).getString("name"));
- map.put("info", JSONObject(i).getString("info"));
- map.put("img",JSONObject(i).getString("photo"));
- list.add(map);
- }
- return list;
-
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
-
-
- return list;
- }
讲解:
1、
[java] view plain copy
- inputStreamAssets().open("my_");
是打开assets文件夹下的my_文件;
2、
[java] view plain copy
- String json=readTextFile(inputStream);
- JSONArray array = new JSONArray(json);
readTextFile()是自己实现的函数,后面给出具体代码,实现将输入流组装成String字符串并返回;
然后将利用json字符串生成JSON数据。
3、后面的代码就是利用jsonArray类的方法了,没什么好讲的。
其中readTextFile()函数是将输入的文件流组装成String字符串返回;实现代码如下:
[java] view plain copy
- public String readTextFile(InputStream inputStream) {
- String readedStr = "";
- BufferedReader br;
- try {
- br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
- String tmp;
- while ((tmp = br.readLine()) != null) {
- readedStr += tmp;
- }
- br.close();
- inputStream.close();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return readedStr;
- }
三、全部代码
[java] view plain copy
- public class MainActivity extends ListActivity{
-
- private List<Map<String, Object>> mData;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- Create(savedInstanceState);
- mData = getData();
- MyAdapter adapter = new MyAdapter(this);
- setListAdapter(adapter);
- }
-
- private List<Map<String, Object>> getData() {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- Map<String, Object> map = new HashMap<String, Object>();
- InputStream inputStream;
- try {
- inputStreamAssets().open("my_");
- String json=readTextFile(inputStream);
- JSONArray array = new JSONArray(json);
- for (int i = 0; i < array.length(); i++) {
- map = new HashMap<String, Object>();
- map.put("name", JSONObject(i).getString("name"));
- map.put("info", JSONObject(i).getString("info"));
- map.put("img",JSONObject(i).getString("photo"));
- list.add(map);
- }
- return list;
-
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
-
-
- return list;
- }
-
-
-
- public final class ViewHolder{
- public ImageView img;
- public TextView name;
- public TextView info;
- }
-
-
-
- public class MyAdapter extends BaseAdapter{
-
- private LayoutInflater mInflater;
-
- public MyAdapter(Context context){
- this.mInflater = LayoutInflater.from(context);
- }
- @Override
- public int getCount() {
- // TODO Auto-generated method stub
- return mData.size();
- }
-
- @Override
- public Object getItem(int arg0) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public long getItemId(int arg0) {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
-
- ViewHolder holder = null;
- if (convertView == null) {
-
- holder=new ViewHolder();
-
- convertView = mInflater.inflate(R.layout.activity_main, null);
- holder.img = (ImageView)convertView.findViewById(R.id.img);
- holder.name = (TextView)convertView.findViewById(R.id.name);
- holder.info = (TextView)convertView.findViewById(R.id.info);
- convertView.setTag(holder);
-
- }else {
-
- holder = (Tag();
- }
-
- holder.img.setImageBitmap(getHome(((position).get("img")));
- holder.name.setText(((position).get("name"));
- holder.info.setText(((position).get("info"));
-
- return convertView;
- }
-
- }
-
- /**
- * 根据图片名称获取主页图片
- */
- public Bitmap getHome(String photo){
- String homeName = photo + ".jpg";
- InputStream is=null;
-
- try {
- is=getAssets().open("home/"+homeName);
- Bitmap bitmap = BitmapFactory.decodeStream(is);
- is.close();
- return bitmap;
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return null;
-
- }
- 工具类
- /**
- *
- * @param inputStream
- * @return
- */
- public String readTextFile(InputStream inputStream) {
- String readedStr = "";
- BufferedReader br;
- try {
- br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
- String tmp;
- while ((tmp = br.readLine()) != null) {
- readedStr += tmp;
- }
- br.close();
- inputStream.close();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return readedStr;
- }
- }
四、讲解如何实现的本地图片绑定
我们在第二部分讲了怎样解析JSON数据,所以在看了全部代码后,会出现一个问题,即:如何实现的JSON数据与IMG图片实现的绑定呢。
这里我们把相关的代码提出来
1、在getView()函数中
[java] view plain copy
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
-
- ViewHolder holder = null;
- if (convertView == null) {
-
- holder=new ViewHolder();
-
- convertView = mInflater.inflate(R.layout.activity_main, null);
- holder.img = (ImageView)convertView.findViewById(R.id.img);
- holder.name = (TextView)convertView.findViewById(R.id.name);
- holder.info = (TextView)convertView.findViewById(R.id.info);
- convertView.setTag(holder);
-
- }else {
-
- holder = (Tag();
- }
-
- holder.img.setImageBitmap(getHome(((position).get("img")));
- holder.name.setText(((position).get("name"));
- holder.info.setText(((position).get("info"));
-
- return convertView;
- }
注意:
1、
[java] view plain copy
- holder.img = (ImageView)convertView.findViewById(R.id.img);
实现将XML元素与viewHolder绑定
2、
[java] view plain copy
- holder.img.setImageBitmap(getHome(((position).get("img")));
注意这里setImageBitmap()传进去的是Bitmap类型数据,也即实现了将XML元素与本地的IMG图片对应起来;这样就实现的XML与本地图片的绑定。
特别注意的是getHome()这个函数,我们知道mData是个list类型数据,通过(position).get("img")可能获得存储在mData中的与“img”这个KEY对应的文件名;
所以getHome()这个函数的功能就是传进去JSON数据中photo字段对应的JPG文件的文件名;输出的是这个文件名对应的Bitmap;
[java] view plain copy
- public Bitmap getHome(String photo){
- String homeName = photo + ".jpg";
- InputStream is=null;
-
- try {
- is=getAssets().open("home/"+homeName);
- Bitmap bitmap = BitmapFactory.decodeStream(is);
- is.close();
- return bitmap;
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return null;
-
- }