前言:前面的一篇博客讲解了怎样使用BaseAdapter,这篇博客讲深入一些,实现从本地的JSON文件读取数据,加载到listView中显示。
先看效果:
再说一下,这篇文章的功能是:在派生自BaseAdapter基础上,从本地JSON文件中读取信息,动态生成listView页面!
这篇文章的XML布局文件没有变,为了大家方便还是贴一下吧。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/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_home_friends.txt):
[{"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数据解析方法
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 {
inputStream=this.getAssets().open("my_home_friends.txt");
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", array.getJSONObject(i).getString("name"));
map.put("info", array.getJSONObject(i).getString("info"));
map.put("img",array.getJSONObject(i).getString("photo"));
list.add(map);
}
return list;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return list;
}
讲解:
1、
inputStream=this.getAssets().open("my_home_friends.txt");
是打开assets文件夹下的my_home_friends.txt文件;
2、
String json=readTextFile(inputStream);
JSONArray array = new JSONArray(json);
readTextFile()是自己实现的函数,后面给出具体代码,实现将输入流组装成String字符串并返回;
然后将利用json字符串生成JSON数据。
3、后面的代码就是利用jsonArray类的方法了,没什么好讲的。
其中readTextFile()函数是将输入的文件流组装成String字符串返回;实现代码如下: 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;
}
三、全部代码
public class MainActivity extends ListActivity{
private List<Map<String, Object>> mData;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(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 {
inputStream=this.getAssets().open("my_home_friends.txt");
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", array.getJSONObject(i).getString("name"));
map.put("info", array.getJSONObject(i).getString("info"));
map.put("img",array.getJSONObject(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 = (ViewHolder)convertView.getTag();
}
holder.img.setImageBitmap(getHome((String)mData.get(position).get("img")));
holder.name.setText((String)mData.get(position).get("name"));
holder.info.setText((String)mData.get(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()函数中
@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 = (ViewHolder)convertView.getTag();
}
holder.img.setImageBitmap(getHome((String)mData.get(position).get("img")));
holder.name.setText((String)mData.get(position).get("name"));
holder.info.setText((String)mData.get(position).get("info"));
return convertView;
}
注意:
1、
holder.img = (ImageView)convertView.findViewById(R.id.img);
实现将XML元素与viewHolder绑定
2、
holder.img.setImageBitmap(getHome((String)mData.get(position).get("img")));
注意这里setImageBitmap()传进去的是Bitmap类型数据,也即实现了将XML元素与本地的IMG图片对应起来;这样就实现的XML与本地图片的绑定。
特别注意的是getHome()这个函数,我们知道mData是个list类型数据,通过mData.get(position).get("img")可能获得存储在mData中的与“img”这个KEY对应的文件名;
所以getHome()这个函数的功能就是传进去JSON数据中photo字段对应的JPG文件的文件名;输出的是这个文件名对应的Bitmap;
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;
}
源码地址:http://download.csdn.net/detail/harvic880925/6705555(不要分,仅供分享)
请大家尊重原作者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/17288687