modul praktikum 11 - android sudaryatno
Post on 24-May-2015
734 Views
Preview:
DESCRIPTION
TRANSCRIPT
Praktikum ANDROID
ANDROID
FOR
BEGINNER MODUL 11 ![ANDROID WORKING WITH JSON API]
!!!!!SUDARYATNO yatnosudar@gmail.com | @dodulz | facebook : yatno.sudar
Page � of �1 10
Praktikum ANDROIDANDROID WORKING WITH JSON API
!NETWORKING
Android memiliki fasilitas untuk akses jaringan intranet maupun internet. Akses yang digunakan
pun beragam mulai dari Socket sampai protokol HTTP. Banyak dari aplikasi android
menggunakan protokol HTTP. Protokol ini sering digunakan untuk upload dan download. Untuk
mengakses jaringan, kita harus menambahkan permission di AndroidManifest.xml.
Untuk mengetahui apakah android terhubung dengan internet atau tidak, kita dapat cek dengan
code berikut :
Tips, lakukan proses networking di background service. Gunakan class AsynTask agar proses
yang dilakukan activity tidak membuat aplikasi kita error.
!JSON API
JSON (JavaScript Object Notation) digunakan sebagai media penghubung antara aplikasi
client dan aplikasi server. Keuntungan dari JSON API lebih ringan dibanding webservice
menggunakan XML. Beberapa contoh platform yang sudah memanfaatkan teknologi JSON seprti
Twitter, Facebook , Instagram, dan lain-lain.
JSON memiliki sturktur yang terdiri Object dan Array. Objet merupakan data tunggal,
sedangkan Array terdiri dari dari banyak Object. Berikut ini contoh dari JSON. JSON Object
ditandai dengan kurung siku “ [ ] ” sedangkan JSON Object ditandai dengan kurung kurawal “ { } ”.
!!
Page � of �2 10
<uses-permission android:name="android.permission.INTERNET" />!<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ConnectivityManager connMgr = (ConnectivityManager) ! getSystemService(Context.CONNECTIVITY_SERVICE);! NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();! if (networkInfo != null && networkInfo.isConnected()) {! // fetch data! } else {! // display error! }
Praktikum ANDROID
Pada JSON diatas, terdiri dari JSON Object dan JSON Array. contacts merupakan JSON Array , id,
name, email, address, gender, phone, mobile, home, office merupakan JSON Object. JSON class di
android terdiri dari dua class, JSONArray dan JSONObject.
!Android Asynchronous Http Client
Adalah library third party yang dibuat oleh James Smith digunakan untuk melakukan akses ke
JSON API dengan mudah. Library ini bersifat Asynchronous yang artinya setiap proses logic yang
dilakukan, diselesaikan tanpa ada prosesi menunggu untuk menyelesaikan proses logic dan
dapat melakukan proses logic yang lain. Namun proses logic akan memberikan callback atau
informasi di kemudian waktu jika proses sudah selesai.
!Contoh di kehidupan nyata sebagai berikut:
Dalam sebuah antrian rumah sakit, untuk menemui dokter kita diwajibkan ke resepsionis dulu
untuk mengisi data diri baru selanjutnnya menemui dokter. Data diri yang harus di isi ada lima
lembar. dan panjang antrian adalah 100 pasien.
!Page � of �3 10
{ "contacts": [ { "id": "c200", "name": "Ravi Tamada", "email": "ravi@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c201", "name": "Johnny Depp", "email": "johnny_depp@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } } ]}
Praktikum ANDROIDA. Penyelesaian Synchronous
Jika diselesaikan secara Synchronous setiap antrian akan mengantri di resepsionis untuk
mengisi data diri sebanyak lima lembar. untuk kemudian selanjutnnya menemui dokter. Bisa di
bayangkan berapa lama waktu yang dibutuhkan untuk si pasien ke 100 bisa menemui dokter.
B. Penyelesaian Asynchronous
Jika diselesaikan secara Asynchronous setiap antrian akan mengambil formulir biodata. Dan diisi
secara mandiri tanpa perlu mengantri di resepsionis. setelah selesai mengisi kemudian
diserahkan keresepsionis dan diperbolehkan untuk menemui dokter.
!Untuk mendownload library ini bisa di situs http://loopj.com/android-async-http/. Berikut ini
adalah fitur yang dapat anda gunakan untuk keperluan Http Client di android :
!• Make asynchronous HTTP requests, handle responses in anonymous callbacks
• HTTP requests happen outside the UI thread
• Requests use a threadpool to cap concurrent resource usage
• GET/POST params builder (RequestParams)
• Multipart file uploads with no additional third party libraries
• Tiny size overhead to your application, only 25kb for everything
• Automatic smart request retries optimized for spotty mobile connections
• Automatic gzip response decoding support for super-fast requests
• Binary file (images etc) downloading with BinaryHttpResponseHandler
• Built-in response parsing into JSON with JsonHttpResponseHandler
• Persistent cookie store, saves cookies into your app’s SharedPreferences
!!
Page � of �4 10
Praktikum ANDROID
PRAKTIKUM !Tujuan : Dapat menggunakan Library Asynchronous Http Client untuk keperluan API dan dapat memahami bentuk-bentuk dari JSON!Scope : AndroidHttpClient, JSONObject, JSONArray, ListView, AsynTask!!1. Buat project baru!2. Edit activity_main.xml dengan code berikut :!
3. Buat file layout dengan nama item_contact.xml dengan code berikut :!
Page � of �5 10
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ListView android:id="@+id/list_contact" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:visibility="gone" > </ListView> <ProgressBar android:id="@+id/progressbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /></RelativeLayout>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/nama" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content"
Praktikum ANDROID
4. Buat file Contacts dengan code sebagai berikut :!
Page � of �6 10
android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/ponsel" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" /></LinearLayout>
public class Contacts { public String id; public String name; public String email; public String address; public String gender; public String phone_mobile; public String phone_home; public String office; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; }
Praktikum ANDROID
5. Buat file AdapterContacts dengan code berikut :!
Page � of �7 10
public String getPhone_mobile() { return phone_mobile; } public void setPhone_mobile(String phone_mobile) { this.phone_mobile = phone_mobile; } public String getPhone_home() { return phone_home; } public void setPhone_home(String phone_home) { this.phone_home = phone_home; } public String getOffice() { return office; } public void setOffice(String office) { this.office = office; }}
public class AdapterContacts extends ArrayAdapter<Contacts>{ public Activity context; public int textViewResourceId = R.layout.item_contacts; public AdapterContacts(Activity context, int textViewResourceId) { super(context, textViewResourceId); this.context = context; this.textViewResourceId = textViewResourceId; } class ViewHolder{ public TextView nama; public TextView mobile; public TextView email; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view==null) { LayoutInflater inflater = context.getLayoutInflater(); view = inflater.inflate(textViewResourceId, parent, false); ViewHolder vh = new ViewHolder(); vh.email = (TextView) view.findViewById(R.id.email); vh.nama = (TextView) view.findViewById(R.id.nama); vh.mobile = (TextView) view.findViewById(R.id.ponsel);
Praktikum ANDROID
6. Edit MainActivity dengan code berikut :!
!
Page � of �8 10
view.setTag(vh); }else{ view = convertView; } Contacts contacts= getItem(position); ViewHolder vc =(ViewHolder) view.getTag(); vc.email.setText(contacts.getEmail()); vc.nama.setText(contacts.getName()); vc.mobile.setText(contacts.getPhone_mobile()); return view; }}
public class MainActivity extends Activity {! private ListView list; private AdapterContacts adapter; private ProgressBar progressBar;! @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);! list = (ListView) findViewById(R.id.list_contact); progressBar = (ProgressBar) findViewById(R.id.progressbar); adapter = new AdapterContacts(MainActivity.this, R.layout.item_contacts); list.setAdapter(adapter);! new bg_process().execute("http://api.androidhive.info/contacts/"); }! @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }
Praktikum ANDROID
!
Page � of �9 10
class bg_process extends AsyncTask<String, Contacts, Boolean> { @Override protected Boolean doInBackground(final String... params) { runOnUiThread(new Runnable() { @Override public void run() { AsyncHttpClient client = new AsyncHttpClient(); client.get(params[0], new JsonHttpResponseHandler() { @Override public void onSuccess(JSONObject response) { progressBar.setVisibility(View.GONE); list.setVisibility(View.VISIBLE); try { JSONArray jsonArray = response.getJSONArray(“contacts"); for (int i = 0; i < jsonArray.length(); i++) { Contacts contacts = new Contacts(); JSONObject jsonObject = jsonArray.getJSONObject(i); contacts.setId(jsonObject.getString("id")); contacts.setName(jsonObject.getString("name")); contacts.setEmail(jsonObject.getString("email")); contacts.setGender(jsonObject.getString("gender")); contacts.setAddress(jsonObject.getString("address"));contacts.setPhone_home(jsonObject.getJSONObject(“phone").getString("home")); contacts.setPhone_mobile(jsonObject.getJSONObject(“phone").getString("mobile")); contacts.setOffice(jsonObject.getJSONObject(“phone").getString("office"));publishProgress(contacts);}
} catch (JSONException e) {e.printStackTrace();
} super.onSuccess(response); } }); } }); return null;} @Override protected void onProgressUpdate(Contacts... values) { adapter.add(values[0]); super.onProgressUpdate(values); } }}
Praktikum ANDROID7. Jalankan Aplikasi !
Tugas :!!1. Buat halaman detail dari contact!2. Hubungkan halaman detail dengan setOnItemClickListener!3. Simpulkan fungsi dari View.GONE dan View.VISIBLE
Page � of �10 10
top related