前言:前面的一篇博客講解了怎樣使用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");
2、
- String json=readTextFile(inputStream);
- JSONArray array = new JSONArray(json);
然後將利用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);
2、
- holder.img.setImageBitmap(getHome((String)mData.get(position).get("img")));
特別注意的是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;
- }