Tuesday, June 2, 2015

MV2002 Android HttpUrlConnection Remote JSON


.
MV2002 Android HttpUrlConnection
As a replacement to HTTP Client, we can use HttpUrlConnection.
Android blog says…
For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should useHttpURLConnection; it is where we will be spending our energy going forward. 
In this tutorial, we will replace HTTP Client library with HttpURLConnection and change
List < NameValuePair > to HashMap<String, String>.
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) Edit JSONParser Class

File: JSONParser.java
package com.example.myvolunteers200;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;
    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {
        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }
        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);
                conn = (HttpURLConnection) urlObj.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Accept-Charset", charset);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.connect();
                paramsString = sbParams.toString();
                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET
            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }
            try {
                urlObj = new URL(url);
                conn = (HttpURLConnection) urlObj.openConnection();
                conn.setDoOutput(false);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept-Charset", charset);
                conn.setConnectTimeout(15000);
                conn.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            Log.d("JSON Parser", "result: " + result.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        conn.disconnect();
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON Object
        return jObj;
    }
}

2) Update Controller Files

Change
List < NameValuePair > params = new ArrayList < NameValuePair > ();
to
HashMap<String, String> params = new HashMap<>();
File: MainActivity.java
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
          HashMap<String, String> params = new HashMap<String, String>();  
   // 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();
  }
 }
}
3) Edit VolunteerActivity
File: VolunteerActivity.java
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";

  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
          HashMap<String, String> params = new HashMap<String, String>();  
   params.put("name", strName);
   params.put("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