.
MV2001 Android HttpClient Remote JSON
According to Android Blog…
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
If you do not understand WEB REST API and Android HTTP Request, read the beginning of this tutorial at http://android-steps.blogspot.my/2015/06/mv101-create-web-api-for-online.html .
|
*
0) Starting Up
Download Project Template and import to your Android IDE.
1) Add a JSON Parser class
File: JSONParser.java
package com.example.myvolunteers200;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List < NameValuePair > params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
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();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
|
2) Edit MainActivity
Add a class to send and receive Get HTTP messages.
package com.example.myvolunteers200;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
public class MainActivity extends Activity {
// JSON Node names
private static final String TAG_RESULT = "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 jryPersons = null;
// Hashmap for ListView
ArrayList < HashMap < String, String >> alsPersons = new ArrayList < HashMap < String, String >> ();
SimpleAdapter adpPersons;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
@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() {
new GetPersons().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetPersons extends AsyncTask < Void, Void, Void > {
private ProgressDialog pDialog;
// URL to get persons JSON
private String url = "http://notarazi.esy.es/myvolunteers/api/volunteers";
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void...arg0) {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
// getting JSON string from URL
JSONObject jobPersons = jParser.makeHttpRequest(url, "GET", params);
// Check your log cat for JSON response
Log.d("Response:", "Response:" + jobPersons.toString());
if (jobPersons.toString() != null) {
try {
// Getting JSON Array node
jryPersons = jobPersons.getJSONArray(TAG_RESULT);
//reset personList
alsPersons.clear();
// looping through All Persons
for (int i = 0; i < jryPersons.length(); i++) {
JSONObject jobPerson = jryPersons.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);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
adpPersons.notifyDataSetChanged();
}
}
}
|
Start.
Get Request sent.
|
Get Request has been responded.
|
3) Edit VolunteerActivity
Add a class to send and receive Post HTTP messages.
package com.example.myvolunteers200;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
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.SimpleAdapter;
import android.widget.Toast;
public class VolunteerActivity extends Activity {
EditText etxName;
EditText etxEmail;
Button btnRegister;
String strName = "", strEmail = "";
// Hashmap for ListView
ArrayList < HashMap < String, String >> alsPersons = new ArrayList < HashMap < String, String >> ();
SimpleAdapter adpPersons;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
@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() {
new RegisterPerson().execute();
}
@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;
}
/**
* Async task class to get json by making HTTP call
* */
private class RegisterPerson extends AsyncTask < Void, Void, Void > {
String url = "http://notarazi.esy.es/myvolunteers/api/volunteers";
List < NameValuePair > params = new ArrayList < NameValuePair > (2);
String strAction="action unknown",
strActionStatus = "status unknown",
strResult = "result unknown";
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(VolunteerActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void...arg0) {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("name", strName));
params.add(new BasicNameValuePair("email", strEmail));
// getting JSON string from URL
JSONObject jobPersons = jParser.makeHttpRequest(url, "POST", params);
// Check your log cat for JSON response
Log.d("Response:", "Response:" + jobPersons.toString());
if (jobPersons.toString() != null) {
try {
// Getting JSON Array node
strAction = jobPersons.getString("action");
strActionStatus = jobPersons.getString("actionstatus");
strResult = jobPersons.getString("result");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
strAction + "\n" + strActionStatus + "\n" + strResult, Toast.LENGTH_SHORT).show();
finish();
}
}
}
|
Registered email detected.
|
Registration succesful
|
DOWNLOAD
REFERENCES:
.
No comments:
Post a Comment