[Android ] JSON PARSER
JSON Parser
Thực hành
Bài 1: Viết chương trình đọc 1 file JSON từ server và phân tích dữ liệu để hiển thị.
1.       Chép
file “contacts” lên localhost.
2.       Tạo
project (version 1.6), đặt tên “docfilejson1”.
3.       Mở
file “manifest” thêm dòng phân quyền như sau:
    <uses-permission android:name="android.permission.INTERNET"/>
4.       Để
thuận tiện ta sẽ tạo ra 1 class mới phục vụ cho việc đọc json. Tạo class mới đặt
tên vd: “JSONParser.java”.  Trong class vừa
tạo khai báo cá biến toàn cục:
          InputStream is=null;
          JSONObject jobj=null;
          String json;
5.       Tiếp
theo ta xây dựng hàm tên getJSONFromUrl. Hàm này nhận vào một chuỗi là đường dẫn
dẫn đến file json trên server. Nó sẽ trả về chuỗi json.
          public JSONObject getJSONFromUrl(String url)
          {
                 try{
                        //khoi tao
                        DefaultHttpClient client=new DefaultHttpClient();
                        HttpPost httppost=new HttpPost(url);
                        //thuc thi , lay ve
noi dung
                        HttpResponse
httpresponse=client.execute(httppost);
                        HttpEntity
httpentity=httpresponse.getEntity();
                        is=httpentity.getContent();
                        //doc du lieu
                        BufferedReader reader=
                                      new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb=new StringBuilder();
                        String line=null;
                        while((line=reader.readLine())!=null)
                        {
                               sb.append(line+"\n");
                        }
                        is.close();
                        json=sb.toString(); //doc StringBuilder
vao chuoi
                        jobj=new JSONObject(json); //dua chuoi vao doi
tuong json
                 }catch(Exception e)
                 {
                        Log.d("loi", e.toString());
                 }
                 return jobj;
          }
6.       Trở
về file java chính. Khởi tạo 1 số biến toàn cục trong class như sau:
   private static String url = "http://10.0.2.2:8080/testandroid/contacts"; 
   // JSON Node names 
   private static final String TAG_CONTACTS = "contacts"; 
   private static final String TAG_ID = "id"; 
   private static final String TAG_NAME = "name"; 
   private static final String TAG_EMAIL = "email"; 
   private static final String TAG_ADDRESS = "address"; 
   private static final String TAG_GENDER = "gender"; 
   private static final String TAG_PHONE = "phone"; 
   private static final String TAG_PHONE_MOBILE = "mobile"; 
   private static final String TAG_PHONE_HOME = "home"; 
   private static final String TAG_PHONE_OFFICE = "office"; 
   // contacts JSONArray 
   JSONArray contacts = null;
7.       Trong
hàm onCreate ta khởi tạo đối tượng JSONParser (đã viết class ở trên) sau đó
dùng hàm getJSONFromUrl để lấy về chuỗi json. Sau đó ta tạo mảng chứa các
contact. Dùng for để duyệt tất cả các phần tử contact. Tương ứng mỗi phần tử
trong mảng contact ta tạo ra đối tượng JSONObject rồi dùng hàm getString để lấy
dữ liệu ra. Lưu ý: Đối với “phone” nó lại là một object chứa các phần tử con là
“mobile”, “home”, “office” nên ta phải lấy ra đối tượng JSONObject “phone” sau
đó mới lấy tiếp dữ liệu con từ nó.
        JSONParser jsonparse=new JSONParser();
        //lay doi tuong json
        JSONObject
jsonobject=jsonparse.getJSONFromUrl(url);
        try{
          //tao mang contacts
          contacts=jsonobject.getJSONArray(TAG_CONTACTS);
          //duyet tung contacts
          for(int i=0;i<contacts.length();i++)
          {
                 //lay ra mot doi
tuong contact
                 JSONObject
onecontact=contacts.getJSONObject(i);
                 //lay du lieu
                 String
id=onecontact.getString(TAG_ID);
                 String name=onecontact.getString(TAG_NAME);
                 String
email=onecontact.getString(TAG_EMAIL);
                 String
address=onecontact.getString(TAG_ADDRESS);
                 String
gender=onecontact.getString(TAG_GENDER);
                 //so phone la la
json Object
                 JSONObject
phone=onecontact.getJSONObject(TAG_PHONE);
                 String
mobile=phone.getString(TAG_PHONE_MOBILE);
                 String
home=phone.getString(TAG_PHONE_HOME);
                 String
office=phone.getString(TAG_PHONE_OFFICE);
                 Log.d("dulieu","id: "+id +" name:"+name+" phone:"+phone);
          }
        }catch(Exception e)
        {
          Log.d("loi",e.toString());
        }
    }
8.       Chạy
và xem kết quả trong Logcat để thấy dữ liệu JSON đã được phân tích.

Bài 2: Update bài 1 lên version cao hơn, đưa dữ liệu vào ListView (dùng AsyncTask).
Hướng dẫn.
1.       Nâng
cấp version lên vd: 4.0.3. Tự làm nhé.
2.       Trên
giao diện chính kéo vào 1 ListView.
3.       Tạo
ra 1 layout mới đặt tên “listviewlayout.xml”. 
Kéo vào 5 TextView đặt tên tuần tự là “name”,”email”,  “mobile”, “home”, “office”.

4.       Trong
file java chính khai báo ListView và ánh xạ nó. Khai báo thêm một ArrayList chứa
các HashMap
   ListView lv;
   ArrayList<HashMap<String,String>>
contactlist= new
ArrayList<HashMap<String,String>>();
5.       Xây
dựng 1 class trong file java chính (chú ý: AsycnTask phải là subclass) tên
ChayNenLayJson kế thừa từ AsyncTask. Override lên 2 hàm là doInBackGround và
onPostExecute.
    class ChayNenLayJson extends
AsyncTask<Void,Void,Void>
    {
          @Override
          protected Void doInBackground(Void... arg0) {
                 // TODO Auto-generated
method stub
                 return null;
          }
          @Override
          protected void onPostExecute(Void
result) {
                 // TODO Auto-generated
method stub
                 super.onPostExecute(result);
          }
    }
6.       Trong
hàm onCreate viết lệnh để chạy AsyncTask
        new ChayNenLayJson().execute();
7.       Cut
toàn bộ đoạn truy xuất JSON và paste vào hàm doInBackGround. Sau lệnh in ra
Logcat thêm lệnh để tạo đối tượng HashMap, lấy các dữ liệu bỏ vào HashMap cuối
cùng add HashMap vào ArrayList. Đến đây ta đã có 1 ArrayList chứa tập hợp các dữ
liệu đã phân tích được từ Json.
JSONParser jsonparse=new JSONParser();
    //lay doi tuong json
    JSONObject
jsonobject=jsonparse.getJSONFromUrl(url);
    try{
          //tao mang contacts
          contacts=jsonobject.getJSONArray(TAG_CONTACTS);
          //duyet tung
contacts
          for(int i=0;i<contacts.length();i++)
          {
                 …………………………………………………….
                 String
office=phone.getString(TAG_PHONE_OFFICE);
                 Log.d("dulieu","id: "+id +" name:"+name+" phone:"+phone);
                 HashMap<String,String>
map=new
HashMap<String,String>();
                 map.put(TAG_ID, id);
                 map.put(TAG_NAME, name);
                 map.put(TAG_EMAIL,email);
                 map.put(TAG_ADDRESS,address);
                 map.put(TAG_GENDER,gender);
                 map.put(TAG_PHONE_MOBILE,mobile);
                 map.put(TAG_PHONE_HOME,home);
                 map.put(TAG_PHONE_OFFICE,office);
                 contactlist.add(map);
          }
    }catch(Exception e)
    {
          Log.d("loi",e.toString());
    }
8.       Trong
hàm onPostExecute viết thêm lệnh để lấy dữ liệu từ ArrayList và đổ lên
ListView.
ListAdapter adapter=new
SimpleAdapter(getApplicationContext(),
          contactlist,
          R.layout.listview_layout,
          new String[]{TAG_NAME,TAG_EMAIL,TAG_PHONE_MOBILE,TAG_PHONE_HOME,TAG_PHONE_OFFICE},
          new int[]{R.id.name,R.id.email,R.id.mobile,R.id.home,R.id.office});
lv.setAdapter(adapter);
9.       Cuối
cùng trong hàm onCreate bắt sự kiện khi một mục trong ListView được chọn
 lv.setOnItemClickListener(new
OnItemClickListener() {
    public void
onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                  long arg3) {
           // TODO Auto-generated method stub
           String
name=((TextView)arg1.findViewById(R.id.name)).getText().toString();
           Toast.makeText(getApplicationContext(),"ban chon
"+name,
Toast.LENGTH_SHORT).show();
    }
});
10.   Chạy
chương trình để thấy dữ liệu đã được đổ lên ListView. Click vào một mục trên
ListView để thấy Toast.

Bài 3: Sửa bài 2 và dùng Handler để điều khiển Thread và update UI. Có thể phát triển thêm để khi click vào một mục trên ListView sẽ mở Activity mới và truyền dữ liệu qua.
 telerik
 
 
 
 
No comments: