讀取本地JSON檔案並顯示
阿新 • • 發佈:2019-02-02
填充完我們的資料集合,就可以放置到Adapter中,並顯示到LsitView中,下面給出完整程式碼,
程式功能:讀取本地JSON檔案,並顯示到LsitView上,下面詳細介紹:
[ 2 { 3 "operator":"admin1", 4 "loginDate":"2012-10-20 10:28:10", 5 "logoutDate":"2012-10-20 10:32:10" 6 }, 7 { 8 "operator":"admin2", 9 "loginDate":"2012-10-22 10:20:10", 10 "logoutDate":"2012-10-22 10:32:10" 11 }, 12 { 13 "operator":"admin3", 14 "loginDate":"2012-10-23 10:28:10", 15 "logoutDate":"2012-10-23 10:32:10" 16 }, 17 { 18 "operator":"admin4", 19 "loginDate":"2012-10-20 10:28:10", 20 "logoutDate":"2012-10-20 10:32:10" 21 } 22 ]
先準備內容如上的"json.txt"檔案,放到專案的assets目錄下(此處可以是本地SD卡只是讀取的方式有些異同)。首先要讀出json.txt的內容,要訪問assets下的資源,需要使用AssetManager類的open(filename)方法,文中省去(AssetManager assetManager = getAssets();)步驟,簡寫為Context.getAssets().open(filename)。open方法返回一個輸入流,我們便可以通過這個流來得到json字串。
/** 2 * 讀取本地檔案中JSON字串 3 * 4 * @param fileName 5 * @return 6 */ 7 private String getJson(String fileName) { 8 9 StringBuilder stringBuilder = new StringBuilder(); 10 try { 11 BufferedReader bf = new BufferedReader(new InputStreamReader( 12 getAssets().open(fileName))); 13 String line; 14 while ((line = bf.readLine()) != null) { 15 stringBuilder.append(line); 16 } 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 return stringBuilder.toString(); 21 }
獲得JSON字串,我們便可以解析,進而得到對我們有用的資料,Adnroid已經加入了org.json.*,所以我對json的操作也變得簡單起來,使用JSONArray array = new JSONArray(str) 就能把我們剛剛得到的JSON串傳化為JSONArray,請注意觀察我們的josn.txt的內容,其中包括了四組資料結構相同的資料,每一組資料看成一個JSONObject(包含了若干鍵值對,很像Map),而這些JSONObject便組成了一組JSONArray陣列,所以我們只要遍歷這個array就可以得到其中的所有JSONObject了,有了JSONObject就可以通過Key獲得對應的Value值了。
1 /**
2 * 將JSON字串轉化為Adapter資料
3 *
4 * @param str
5 */
6 private void setData(String str) {
7 try {
8 JSONArray array = new JSONArray(str);
9 int len = array.length();
10 Map<String, String> map;
11 for (int i = 0; i < len; i++) {
12 JSONObject object = array.getJSONObject(i);
13 map = new HashMap<String, String>();
14 map.put("operator", object.getString("operator"));
15 map.put("loginDate", object.getString("loginDate"));
16 map.put("logoutDate", object.getString("logoutDate"));
17 data.add(map);
18 }
19 } catch (JSONException e) {
20 e.printStackTrace();
21 }
22 }
填充完我們的資料集合,就可以放置到Adapter中,並顯示到LsitView中,下面給出完整程式碼,
json.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent"
5 android:orientation="vertical" >
6
7 <ListView
8 android:id="@+id/listView"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content" >
11 </ListView>
12
13 </LinearLayout>
json_item.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent" >
5
6 <TextView
7 android:id="@+id/operator_tv"
8 android:layout_width="fill_parent"
9 android:layout_height="wrap_content"
10 android:layout_marginLeft="15dp" />
11
12 <TextView
13 android:id="@+id/loginDate_tv"
14 android:layout_width="wrap_content"
15 android:layout_height="wrap_content"
16 android:layout_alignLeft="@id/operator_tv"
17 android:layout_below="@id/operator_tv" />
18
19 <TextView
20 android:id="@+id/logoutDate_tv"
21 android:layout_width="wrap_content"
22 android:layout_height="wrap_content"
23 android:layout_alignTop="@+id/loginDate_tv"
24 android:layout_marginLeft="15dp"
25 android:layout_toRightOf="@+id/loginDate_tv" />
26
27 </RelativeLayout>
1 public class JSONTextActivity extends Activity {
2
3 private ListView listView;
4 private List<Map<String, String>> data;
5 private final static String fileName = "json.txt";
6 private ProgressDialog pd;
7
8 @Override
9 protected void onCreate(Bundle savedInstanceState) {
10 super.onCreate(savedInstanceState);
11 setContentView(R.layout.json);
12 init();
13 pd.show();
14 new DataThread().start();
15
16 }
17
18 /**
19 * 初始化
20 */
21 private void init() {
22 listView = (ListView) findViewById(R.id.listView);
23 data = new ArrayList<Map<String, String>>();
24 pd = new ProgressDialog(this);
25 pd.setMessage("資料載入中……");
26
27 }
28
29 /**
30 * 載入資料執行緒
31 */
32 class DataThread extends Thread {
33
34 @Override
35 public void run() {
36 String jsonStr = getJson(fileName);
37 setData(jsonStr);
38 dataHandler.sendMessage(dataHandler.obtainMessage());
39 }
40
41 }
42
43 /**
44 * 載入資料執行緒完成處理Handler
45 */
46 Handler dataHandler = new Handler() {
47
48 public void handleMessage(android.os.Message msg) {
49 if (pd != null) {
50 pd.dismiss();
51 }
52 SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
53 data, R.layout.json_item, new String[] { "operator",
54 "loginDate", "logoutDate" }, new int[] {
55 R.id.operator_tv, R.id.loginDate_tv,
56 R.id.logoutDate_tv });
57 listView.setAdapter(adapter);
58 }
59 };
60
61 /**
62 * 讀取本地檔案中JSON字串
63 *
64 * @param fileName
65 * @return
66 */
67 private String getJson(String fileName) {
68
69 StringBuilder stringBuilder = new StringBuilder();
70 try {
71 BufferedReader bf = new BufferedReader(new InputStreamReader(
72 getAssets().open(fileName)));
73 String line;
74 while ((line = bf.readLine()) != null) {
75 stringBuilder.append(line);
76 }
77 } catch (IOException e) {
78 e.printStackTrace();
79 }
80 return stringBuilder.toString();
81 }
82
83 /**
84 * 將JSON字串轉化為Adapter資料
85 *
86 * @param str
87 */
88 private void setData(String str) {
89 try {
90 JSONArray array = new JSONArray(str);
91 int len = array.length();
92 Map<String, String> map;
93 for (int i = 0; i < len; i++) {
94 JSONObject object = array.getJSONObject(i);
95 map = new HashMap<String, String>();
96 map.put("operator", object.getString("operator"));
97 map.put("loginDate", object.getString("loginDate"));
98 map.put("logoutDate", object.getString("logoutDate"));
99 data.add(map);
100 }
101 } catch (JSONException e) {
102 e.printStackTrace();
103 }
104 }
105 }