.
MV2004 Android Volley JSON Data Request
We are going to modify our MyVolunteers Apps so that it uses Volley Library.
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
It is recommended that we create a Volley singleton class to handle all requests.
It has been reported that Volley JsonObjectRequest Post request not working, therefore it is recommended that we create a helper class.
|
0) Starting Up
Download Project Template:
Download Volley Jar file
Put the jar file into the libs folder.
If you are using Android Studio, scroll down to read the the section Z) Import Volley Library Into Project.
1) Volley Class Codes
1.1) Add A Volley Singleton Class
File: RestApplication.java
package com.example.myvolunteers200;
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 RestApplication extends Application {
public static final String TAG = RestApplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private static RestApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized RestApplication 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);
}
}
}
|
1.2) Add a Custom Request Class
File: CustomRequest.java
package com.example.myvolunteers200;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
|
2) Update AndroidManifest
File: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myvolunteers200"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name="com.example.myvolunteers200.RestApplication" >
<activity
android:name="com.example.myvolunteers200.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>
<activity
android:name="com.example.myvolunteers200.VolunteerActivity"
android:label="@string/title_activity_volunteer" >
</activity>
</application>
</manifest>
|
3) Update Controller Class
3.1) Main Activity
File: MainActivity.java
package com.example.myvolunteers200;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.JsonObjectRequest;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
// JSON Node names
private static final String TAG_PERSONS= "result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
// persons JSONArray
JSONArray persons = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> alsPersons = new ArrayList<HashMap<String, String>>();
SimpleAdapter adpPersons;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViewObjects();
}
@Override
public void onResume() {
super.onResume(); // Always call the superclass method first
refreshList();
}
private void setViewObjects() {
//bind ListView
ListView mListView = (ListView) findViewById(R.id.lvw_persons);
//set adapter
adpPersons = new SimpleAdapter(MainActivity.this, alsPersons,
R.layout.activity_main_list_item, new String[] { TAG_NAME, TAG_EMAIL,}
, new int[] { R.id.name,R.id.email}
);
//plug adapter to ListView
mListView.setAdapter(adpPersons);
//bind ImageView
ImageView imvPerson =(ImageView) findViewById(R.id.imv_person);
//attach onClickListener to ImageView
imvPerson.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Toast.makeText(getApplicationContext(), "Add Person", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, VolunteerActivity.class));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings:
//
case R.id.menu_refresh:
refreshList();
default:
return super.onOptionsItemSelected(item);
}
}
private void refreshList() {
//Toast.makeText(getApplicationContext(), "Refresh List", Toast.LENGTH_SHORT).show();
getPersons();
}
/**
* Method to make json object request where json response starts wtih {
* */
private void getPersons() {
final ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
String urlJsonObj = "http://notarazi.esy.es/myvolunteers/api/volunteers";
// Showing progress dialog
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlJsonObj, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response:", "Response:" + response.toString());
try {
// Getting JSON Array node
persons = response.getJSONArray(TAG_PERSONS);
//reset personList
alsPersons.clear();
// looping through All Persons
for (int i = 0; i < persons.length(); i++) {
JSONObject jobPerson = persons.getJSONObject(i);
String id = jobPerson.getString(TAG_ID);
String name = jobPerson.getString(TAG_NAME);
String email = jobPerson.getString(TAG_EMAIL);
// tmp hashmap for single person
HashMap < String, String > hmpPerson = new HashMap < String, String > ();
// adding each child node to HashMap key => value
hmpPerson.put(TAG_ID, id);
hmpPerson.put(TAG_NAME, name);
hmpPerson.put(TAG_EMAIL, email);
// adding person to person list
alsPersons.add(hmpPerson);
/**
* Updating parsed JSON data into ListView
* */
adpPersons.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// Dismiss the progress dialog
if (pDialog.isShowing()) pDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Response", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
// Dismiss the progress dialog
if (pDialog.isShowing()) pDialog.dismiss();
}
});
// Adding request to request queue
RestApplication.getInstance().addToRequestQueue(jsonObjReq);
}
}
|
3.2) Volunteers Activity
File: VolunteersActivity.java
package com.example.myvolunteers200;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.JsonObjectRequest;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class VolunteerActivity extends Activity {
EditText etxName;
EditText etxEmail;
Button btnRegister;
String strName="", strEmail="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volunteer);
setViewObjects();
}
private void setViewObjects() {
etxName = (EditText) findViewById(R.id.etx_name);
etxEmail = (EditText) findViewById(R.id.etx_email);
btnRegister = (Button) findViewById(R.id.btn_register);
btnRegister.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (isValidFormData()) {
strName=etxName.getText().toString();
strEmail=etxEmail.getText().toString();
registerData();
}
}
private boolean isValidFormData() {
boolean isName = false, isEmail = false;
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
String strTestValue = "";
//get field values
strTestValue = etxName.getText().toString();
//check field values validity
if (isEmptyString(strTestValue)) {
etxName.setError("Name must not be empty");
Toast.makeText(getApplicationContext(), "Name error", Toast.LENGTH_SHORT).show();
} else {
isName = true;
}
//get field values
strTestValue = etxEmail.getText().toString();
//check field values validity
if (isEmptyString(strTestValue)) {
etxEmail.setError("Email must not be empty");
Toast.makeText(getApplicationContext(), "Email error", Toast.LENGTH_SHORT).show();
} else {
if (strTestValue.matches(emailPattern)) {
isEmail = true;
} else {
etxEmail.setError("Enter valid Email format");
Toast.makeText(getApplicationContext(), "Email error", Toast.LENGTH_SHORT).show();
}
}
return (isName && isEmail);
}
// validating empty string
public boolean isEmptyString(String text) {
return (text == null || text.trim().equals("null") || text.trim()
.length() <= 0);
}
});
}
private void registerData() {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "Registering...", Toast.LENGTH_SHORT).show();
//finish();
setPerson();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_volunteer, menu);
return true;
}
/**
* Method to make json object request where json response starts wtih {
* */
private void setPerson() {
final ProgressDialog pDialog = new ProgressDialog(VolunteerActivity.this);
String urlJsonObj = "http://notarazi.esy.es/myvolunteers/api/volunteers";
// Showing progress dialog
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
CustomRequest jsonObjReq = new CustomRequest(Method.POST, urlJsonObj, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response:", "Response:" + response.toString());
if (response.toString() != null) {
try {
String strAction = "action unknown",
strActionStatus = "status unknown",
strResult = "result unknown";
// Getting Response Summary
strAction = response.getString("action");
strActionStatus = response.getString("actionstatus");
strResult = response.getString("result");
Toast.makeText(getApplicationContext(),
strAction + "\n" + strActionStatus + "\n" + strResult, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
// Dismiss the progress dialog
if (pDialog.isShowing()) pDialog.dismiss();
finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Response:", "Response:" + error.toString());
// Dismiss the progress dialog
if (pDialog.isShowing()) pDialog.dismiss();
finish();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("name", strName);
params.put("email", strEmail);
return params;
}
}
;
// Adding request to request queue
RestApplication.getInstance().addToRequestQueue(jsonObjReq);
}
}
|
DOWNLOAD
REFERENCES
Z) Import Volley Library Into Project
Z.1) Download Volley Project
Z.2) Import using Android Studio
Z.3) Add Dependencies
Build.Gradle(Module:App)
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.notarazi.myvolleyjsonarray1"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:23.1.0'
compile project(':volley')
}
|
Sync Project with Gradle Files
No comments:
Post a Comment