[Android] Chương Trình đọc 1 File JSON Từ Server Và Phân Tích Dữ ...

droidcourse - Android, ASO, Admob, Make money with your Android/IOS Apps

Header Ads

Home android [Android] Chương trình đọc 1 file JSON từ server và phân tích dữ liệu để hiển thị [Android] Chương trình đọc 1 file JSON từ server và phân tích dữ liệu để hiển thị 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. (sử dụng Appservxem hướng dẫn cài đặt tại đây) 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()); } returnjobj; } 6.Trở về file java chính. Khởi tạo 1 số biến toàn cục trong class như sau: privatestatic String url = "http://10.0.2.2:8080/testandroid/contacts"; // JSON Node names privatestaticfinal String TAG_CONTACTS = "contacts"; privatestaticfinal String TAG_ID = "id"; privatestaticfinal String TAG_NAME = "name"; privatestaticfinal String TAG_EMAIL = "email"; privatestaticfinal String TAG_ADDRESS = "address"; privatestaticfinal String TAG_GENDER = "gender"; privatestaticfinal String TAG_PHONE = "phone"; privatestaticfinal String TAG_PHONE_MOBILE = "mobile"; privatestaticfinal String TAG_PHONE_HOME = "home"; privatestaticfinal 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 returnnull; } @Override protectedvoid 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}, newint[]{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() { publicvoid 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. [Android] Chương trình đọc 1 file JSON từ server và phân tích dữ liệu để hiển thị [Android] Chương trình đọc 1 file JSON từ server và phân tích dữ liệu để hiển thị Reviewed by Thanh Nguyen on 18:59 Rating: 5 Tags : android SHARE THIS Share it Tweet Share it Share it Pin it android

No comments:

Subscribe to: Post Comments ( Atom )

Recent Posts

3/recentposts

Facebook

Author Details

@droidcourse Android, ASO, Admob, Make money with your Android/IOS Apps. Learning Golang, React Native, Machine Learning blog

Popular Posts

  • 6 uncommon principles for effective data science Motivation The more I delve in data science, the more convinced I am that companies and data science practitioners must have a clear view o...
  • The 5 biggest announcements from Apple’s March event After a week of nearly daily hardware updates leading up to today, Apple finally unveiled its software news with an onslaught of new subscr...
  • Who is Data Scientist and why Data Science Matters In the first post of our series on building data-informed companies, we shared the most important ingredients needed to build a data-infor...
  • First Build An Audience. Then Make Products Lesson Recap 1. Building an audience first allows you to research and test which potential products people want most.
Powered by Blogger.

About

droidcourse - Android, ASO, Admob, Make money with your Android/IOS Apps. Learning Golang, React Native, Machine Learning blog

Best of week

  • 6 uncommon principles for effective data science Motivation The more I delve in data science, the more convinced I am that companies and data science practitioners must have a clear view o...
  • History of Humanity Wonderful artwork by Milo Manara, depicting human history.  Sex , war to gain sex, more war to gain riches to have more sex.
  • Android source code - Quotes app Quotes app is an android application.Quotes App has user-friendly interface with easy to manage. The Quotes are stored in Serve...
  • Android Animate Fade In/Fade Out tutorial and sourcecode Hello , today i'll show you the easiest way to make animation fade in/ fade out in android Download  Sample SourceCode

Popular Posts

  • 6 uncommon principles for effective data science Motivation The more I delve in data science, the more convinced I am that companies and data science practitioners must have a clear view o...
  • The 5 biggest announcements from Apple’s March event After a week of nearly daily hardware updates leading up to today, Apple finally unveiled its software news with an onslaught of new subscr...
Created By droidcourse.com & droidcourse.com | Distributed By droidcourse.com

Từ khóa » đọc File Json Trong Android