Monday, June 1, 2015

MV103 Android HttpClient Post Method and Remote JSON Data


.

MV103 Android HttpClient Post Method and Remote JSON Data

0) Starting Up

1) Add a new activity.

Right-click the project name, select New/Other...
Select Android Activity.
Select Blank Activity.
Give a name “VolunteerActivity” and click Finish.
Check Project Navigator.

2) Edit Resources for New Activity (Volunteer)

2.1) Add Image

person_small.png
Save the above image as res/drawable/person_small.png

2.2) Layout

res/layout/activity_volunteer.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SettingsActivity" >
   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/person_small"
        android:layout_marginTop="20dp"
       android:layout_gravity="center_horizontal"
       />
    <EditText
        android:id="@+id/etx_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="Name" />
    <EditText
        android:id="@+id/etx_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="Email" />
    <Button
        android:id="@+id/btn_register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Register"
        android:background="#e6e6e6" />
     
</LinearLayout>
OUTCOME.

3) Edit Main Controller

3.1) Start Volunteer Activity

MainActivity.java
package com.example.myvolunteers102;
import java.util.ArrayList;
import java.util.HashMap;
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.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();
               new GetPersons().execute();
           }
           
           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:
                           new GetPersons().execute();  
                   default:
                       return super.onOptionsItemSelected(item);
               }
           }          
           /**
            * 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) {
                   // Creating service handler class instance
                   ServiceHandler sh = new ServiceHandler();
                   // Making a request to url and getting response
                   String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
                   Log.d("Response: ", "> " + jsonStr);
                   if (jsonStr != null) {
                       try {
                           JSONObject jsonObj = new JSONObject(jsonStr);
                           // Getting JSON Array node
                           JSONArray arrPersons = jsonObj.getJSONArray(TAG_PERSONS);
                           //reset personList
                           alsPersons.clear();
                           
                           // looping through All Persons
                           for (int i = 0; i < arrPersons.length(); i++) {
                               JSONObject jobPerson = arrPersons.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;
               }
               @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();
               }
           }
        }
OUTCOME.
Start.
Click the Add Volunteer button.
Volunteer Activity Page is displayed

3.2) Automatically refresh the Main Activity when Back Button is pressed in Volunteer Activity

Move the method call from onCreate method to onResume  method.
package com.example.myvolunteers102;
import java.util.ArrayList;
import java.util.HashMap;
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.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();
               //new GetPersons().execute();
           }
           @Override
               public void onResume() {
                   super.onResume();  // Always call the superclass method first
                   new GetPersons().execute();
               }
           
           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:
                           new GetPersons().execute();  
                   default:
                       return super.onOptionsItemSelected(item);
               }
           }          
           /**
            * 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) {
                   // Creating service handler class instance
                   ServiceHandler sh = new ServiceHandler();
                   // Making a request to url and getting response
                   String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
                   Log.d("Response: ", "> " + jsonStr);
                   if (jsonStr != null) {
                       try {
                           JSONObject jsonObj = new JSONObject(jsonStr);
                           // Getting JSON Array node
                           JSONArray arrPersons = jsonObj.getJSONArray(TAG_PERSONS);
                           //reset personList
                           alsPersons.clear();
                           
                           // looping through All Persons
                           for (int i = 0; i < arrPersons.length(); i++) {
                               JSONObject jobPerson = arrPersons.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;
               }
               @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();
               }
           }
        }
OUTCOME.
Start.
Click the Add Volunteer button.
Volunteer Activity Page is displayed
When the Back Button is pressed in Volunteer Activity Page, the apps goes back to Main Activity and automatically refreshes the list.

4) Edit Volunteer Activity

The activity calls the setViewObjects during the onCreate event.
When the user clicks the Register Button, the apps checks that the input is not empty and according to the valid format.
Then it prepares to register to the cloud.

4.1) Set The View Objects

File: VolunteerActivity.java
package com.example.myvolunteers102;
import android.os.Bundle;
import android.app.Activity;
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;
         
        @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() {
                   public void onClick(View view) {
                    if (isValidFormData()) {
                     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();
                 }
        @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;
        }
}
Name error
Email error
Valid inputs accepted and the Apps is ready to register the details.

4.2) Send Post Method Request

VolunteerActivity.java
package com.example.myvolunteers102;
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.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.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();
                 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 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();
                   
                   params.add(new BasicNameValuePair("name",strName));
                   params.add(new BasicNameValuePair("email",strEmail));
               }
               @Override
               protected Void doInBackground(Void... arg0) {
                   // Creating service handler class instance
                   ServiceHandler sh = new ServiceHandler();
                   // Making a request to url and getting response
                   
                   String jsonStr = sh.makeServiceCall(url,ServiceHandler.POST,params);
                   Log.d("Response: ", "> " + jsonStr);
                   if (jsonStr != null) {
                       try {
                           JSONObject jsonObj = new JSONObject(jsonStr);
                           // Getting JSON Array node
                           
                           strActionStatus =jsonObj.getString("actionstatus");
                           strResult =jsonObj.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(), strActionStatus + "\n" + strResult, Toast.LENGTH_SHORT).show();
                   finish();
                   
               }
           }
}
Enter a new volunteer.
Click register.
If successful, you get a toast showing “success” and id number.
The activity automatically closes itself.
The Main Activity refreshes the list.
The new volunteer name should be displayed at the bottom of the list.

DOWNLOAD

REFERENCES:


.

No comments:

Post a Comment