Wednesday 10 September 2014

Json parsing using volley



Json parsing using volley

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.
Volley offers the following benefits:
  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

Json parsing using volley example

1.Create new project.

2.add volley.jar in your libs.clickhere to download vollery.jar.

3.Create AppController.java Singleton class where we initialize all the volley core libs.


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 <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}


4.add the AppController.java into the Application tag in manifest.xml to execute this at app launch.and also add internet permission.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidtoppers.volleyexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:name="com.androidtoppers.volleyexample.AppController"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


5.Create two buttons in the MainActivity layout for call json object request and json array request.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingTop="50dp"
tools:context=".MainActivity" >

<Button
android:id="@+id/json_obj"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_orange_dark"
android:padding="5dp"
android:text="@string/json_obj"
android:textColor="#FFFFFF" />

<Button
android:id="@+id/json_array"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@android:color/holo_orange_dark"
android:padding="5dp"
android:text="@string/json_array"
android:textColor="#FFFFFF" />

<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:scrollbars="vertical"
android:textColor="#FFFFFF" />

</LinearLayout>


6.get the json object and json array requst URL.

Here I am using follow URL.

Json object request URL:
private String jsonObjUrl=
"http://www.androidtoppers.com/VolleyExample/ws_API/get_obj.php";


Response:
{
"id": "12",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image8.jpg",
"dec": "car 8"
}


Json Array request URL:
private String jsonArrayUrl=
"http://www.androidtoppers.com/VolleyExample/ws_API/get_array.php";


Response:
[
{
"id": "1",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image1.jpg",
"dec": "Car 1"
},
{
"id": "2",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image2.jpg",
"dec": "car 2"
},
{
"id": "4",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image3.jpg",
"dec": "car 3 "
},
{
"id": "6",
"Name": "Bentley",
"image": "http://www.androidtoppers.com/photos/webservice/image4.jpg",
"dec": "car 4"
},
{
"id": "7",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image5.jpg",
"dec": "Car 5"
},
{
"id": "10",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image6.jpg",
"dec": "car 6"
},
{
"id": "11",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image7.jpg",
"dec": "car 7"
},
{
"id": "12",
"Name": "BMW",
"image": "http://www.androidtoppers.com/photos/webservice/image8.jpg",
"dec": "car 8"
}
]


7.Create button and class the jsonObjRequest() and jsonArrayReq() from the button in the MainActivity.java
private Button jsonObj,jsonArray;
private TextView textview;
private ProgressDialog mdialog;
private String jsonObjUrl="http://www.androidtoppers.com/VolleyExample/ws_API/get_obj.php";
private String jsonArrayUrl="http://www.androidtoppers.com/VolleyExample/ws_API/get_array.php";
private static String TAG = MainActivity.class.getSimpleName();
private StringBuilder str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jsonObj=(Button)findViewById(R.id.json_obj);
jsonObj.setOnClickListener(this);
jsonArray=(Button)findViewById(R.id.json_array);
jsonArray.setOnClickListener(this);
textview=(TextView)findViewById(R.id.textview);
textview.setMovementMethod(new ScrollingMovementMethod());
mdialog=new ProgressDialog(this);
mdialog.setMessage("Loading..");
mdialog.setCancelable(false);
str=new StringBuilder();
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.json_obj:
jsonArray.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
jsonObj.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_light));
textview.setText("");
str.delete(0, str.length());
callJsonObjRequest();
break;
case R.id.json_array:
jsonObj.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
jsonArray.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_light));
textview.setText("");
str.delete(0, str.length());
callJsonArrayRequest();
break;

default:
break;
}
}
private void dismissDialog() {
// TODO Auto-generated method stub
if(mdialog.isShowing()){
mdialog.dismiss();
}
}

private void showDialog() {
// TODO Auto-generated method stub
if(!mdialog.isShowing()){
mdialog.show();
}
}


callJsonObjRequest:
showDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
jsonObjUrl, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String name = response.getString("Name");
String image=response.getString("image");
String dec=response.getString("dec");
str.append("Name : ").append(name).append("\n").append("Image : ").append(image).append("\n").append("Dec : ").append(dec);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
textview.setText(str);
dismissDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
// hide the progress dialog
dismissDialog();
}
});


callJsonArrayRequest:
showDialog();
JsonArrayRequest jsonarrayReq = new JsonArrayRequest(jsonArrayUrl,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String name = person.getString("Name");
String image=person.getString("image");
String dec=person.getString("dec");
str.append("Name : ").append(name).append("\n").append("Image : ").append(image).append("\n").append("Dec : ").append(dec).append("\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
textview.setText(str);
dismissDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
dismissDialog();
}
});


finally add the request url to the requestQueue


AppController.getInstance().addToRequestQueue(jsonarrayReq);

the full code of mainactivity is,

MainActivity.java
public class MainActivity extends Activity implements OnClickListener{

private Button jsonObj,jsonArray;
private TextView textview;
private ProgressDialog mdialog;
private String jsonObjUrl="http://www.androidtoppers.com/VolleyExample/ws_API/get_obj.php";
private String jsonArrayUrl="http://www.androidtoppers.com/VolleyExample/ws_API/get_array.php";
private static String TAG = MainActivity.class.getSimpleName();
private StringBuilder str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jsonObj=(Button)findViewById(R.id.json_obj);
jsonObj.setOnClickListener(this);
jsonArray=(Button)findViewById(R.id.json_array);
jsonArray.setOnClickListener(this);
textview=(TextView)findViewById(R.id.textview);
textview.setMovementMethod(new ScrollingMovementMethod());
mdialog=new ProgressDialog(this);
mdialog.setMessage("Loading..");
mdialog.setCancelable(false);
str=new StringBuilder();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.json_obj:
jsonArray.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
jsonObj.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_light));
textview.setText("");
str.delete(0, str.length());
callJsonObjRequest();
break;
case R.id.json_array:
jsonObj.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
jsonArray.setBackgroundColor(getResources().getColor(android.R.color.holo_orange_light));
textview.setText("");
str.delete(0, str.length());
callJsonArrayRequest();
break;
default:
break;
}
}
private void callJsonObjRequest() {
// TODO Auto-generated method stub
//show dialog
showDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
jsonObjUrl, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String name = response.getString("Name");
String image=response.getString("image");
String dec=response.getString("dec");
str.append("Name : ").append(name).append("\n").append("Image : ").append(image).append("\n").append("Dec : ").append(dec);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
textview.setText(str);
dismissDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
// hide the progress dialog
dismissDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
private void callJsonArrayRequest() {
// TODO Auto-generated method stub
//show dialog
showDialog();
JsonArrayRequest jsonarrayReq = new JsonArrayRequest(jsonArrayUrl,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String name = person.getString("Name");
String image=person.getString("image");
String dec=person.getString("dec");
str.append("Name : ").append(name).append("\n").append("Image : ").append(image).append("\n").append("Dec : ").append(dec).append("\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
textview.setText(str);
dismissDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
dismissDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonarrayReq);
}
private void dismissDialog() {
// TODO Auto-generated method stub
if(mdialog.isShowing()){
mdialog.dismiss();
}
}
private void showDialog() {
// TODO Auto-generated method stub
if(!mdialog.isShowing()){
mdialog.show();
}
}
}



Screenshot:




No comments: