Tuesday, June 2, 2015

MV2003 Android Loopj Asynchronous Http Client


.
MV2003 Android Loopj Asynchronous Http Client
We are going to modify our MyVolunteers Apps so that it uses loopj. Why loopj?
*

0) Starting Up

Download Project Template:
Download android-async-http jar file:
Put the jar file into the libs folder.
If you are using Android Studio then add dependencies item,
dependencies {
 compile 'com.loopj.android:android-async-http:1.4.4'
}

1) Add Rest Client Class

File: RestClient.java
package com.example.myvolunteers200;
import com.loopj.android.http.*;
public class RestClient {
 private static final String BASE_URL = "http://notarazi.esy.es/myvolunteers/api/";
 private static AsyncHttpClient client = new AsyncHttpClient();
 public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
  client.get(getAbsoluteUrl(url), params, responseHandler);
 }
 public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
  client.post(getAbsoluteUrl(url), params, responseHandler);
 }
 private static String getAbsoluteUrl(String relativeUrl) {
  return BASE_URL + relativeUrl;
 }
}

2) Update Controller Class

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.loopj.android.http.JsonHttpResponseHandler;
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();
  new RestClientUsage().getPersons();
 }
 private class RestClientUsage {
  public void getPersons() {
   final ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
   RestClient.get("volunteers", null, new JsonHttpResponseHandler() {
    @Override
    public void onStart() {
     // called before request is started
     // Showing progress dialog
     pDialog.setMessage("Please wait...");
     pDialog.setCancelable(false);
     pDialog.show();
    }
    public void onSuccess(int statusCode, JSONObject response) {
     // If the response is JSONObject instead of expected JSONArray
     Log.d("Response:", "Response:" + response.toString());
     if (response.toString() != null) {
      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);
       }
      } 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();
     /**
      * Updating parsed JSON data into ListView
      * */
     adpPersons.notifyDataSetChanged();
    }
   });
  }
 }
}
File: VolunteerActivity.java
package com.example.myvolunteers200;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
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 = "";
 // persons JSONArray
 JSONArray persons = null;
 @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();
  // Building Parameters
  RequestParams params = new RequestParams();
  params.put("name", strName);
  params.put("email", strEmail);
  new RestClientUsage().setPerson(params);
 }
 @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;
 }
 private class RestClientUsage {
  public void setPerson(RequestParams params) {
   final ProgressDialog pDialog = new ProgressDialog(VolunteerActivity.this);
   RestClient.post("volunteers", params, new JsonHttpResponseHandler() {
    @Override
    public void onStart() {
     // called before request is started
     // Showing progress dialog
     pDialog.setMessage("Please wait...");
     pDialog.setCancelable(false);
     pDialog.show();
    }
    public void onSuccess(int statusCode, JSONObject response) {
     // If the response is JSONObject instead of expected JSONArray
     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();
    }
   });
  }
 }
}

DOWNLOAD

REFERENCES


.

No comments:

Post a Comment