بِسْÙ…ِ اللَّÙ‡ِ الرَّØْÙ…َÙ†ِ الرَّØِيم
Postingan kali ini ane akan menuliskan Bagaimana Cara Parsing Data menggunakan format Json pada Aplikasi Android, sebelumnya kenali dahulu format json dan komposisi nya.
1. Format Json Array
{ "name" : "Ravi Tamada", "email" : "ravi8x@gmail.com", "phone" : { "home" : "08947 000000", "mobile" : "9999999999" } } |
Sebelum menampilkan script java Android, perhatikan hal penting ini:
1. Download volley.jar dan gunakan pada project anda, karena untuk mengolah data json ini menggunakan Fungsi yang ada di Library Volley.
2. Gunakan App Controller di bawah ini pada Manifest.xml
AppController.java package info.androidhive.volleyjson.app;
Berikut file AppController.java
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public void addToRequestQueue(Request req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public void addToRequestQueue(Request req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Berikut script Java Android Parsing Json Array:
private void makeJsonObjectRequest() {
showpDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlJsonObj, null, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
String name = response.getString("name");
String email = response.getString("email");
JSONObject phone = response.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse = "";
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n";
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
1. Format Json Object
[ { "name" : "Ravi Tamada", "email" : "ravi8x@gmail.com", "phone" : { "home" : "08947 000000", "mobile" : "9999999999" } }, { "name" : "Tommy", "email" : "tommy@gmail.com", "phone" : { "home" : "08946 000000", "mobile" : "0000000000" } }] |
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Script Lengkap MainActivity.java
MainActivity.java
package info.androidhive.volleyjson;
import info.androidhive.volleyjson.R;
import info.androidhive.volleyjson.app.AppController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
public class MainActivity extends Activity {
// json object response url
private String urlJsonObj = "http://api.androidhive.info/volley/person_object.json";
// json array response url
private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
private static String TAG = MainActivity.class.getSimpleName();
private Button btnMakeObjectRequest, btnMakeArrayRequest;
// Progress dialog
private ProgressDialog pDialog;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMakeObjectRequest = (Button) findViewById(R.id.btnObjRequest);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
btnMakeObjectRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// making json object request
makeJsonObjectRequest();
}
});
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// making json array request
makeJsonArrayRequest();
}
});
}
/**
* Method to make json object request where json response starts wtih {
* */
private void makeJsonObjectRequest() {
showpDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlJsonObj, null, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
String name = response.getString("name");
String email = response.getString("email");
JSONObject phone = response.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse = "";
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n";
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Untuk lebih lengkapnya mengenai Library Volley bisa mengunjungi situs ini Android working with Volley Library.
0 komentar:
Post a Comment