Tuesday, December 30, 2014

The story of a dream chaser

Here is my story of the journey to become an able software engineer...

The dream-chaser...

Friday, October 31, 2014

Generic Asynchronous Task for HTTP connection in Android

As I was working on the development of an Android app,  i created a generic Asynchronous task for HTTP connection. I thought its a idea to share it here.

The HttpAsyncTask class


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
 
 private CallBack mCb;
 HashMap<Object, Object> mData = null;
 //List mParams= new ArrayList();
 HashMap<Object, Object> mParams = new HashMap<Object, Object>();
 String mTypeOfRequest;
 String mStrToBeAppended = "";
 boolean isPostDataInJSONFormat = false;
 JSONObject mJSONPostData = null;
 Context mContext = null;
 
 public HTTPAsyncTask(Context context, CallBack c, HashMap<Object, Object> data, JSONObject jsonObj, String request) {
  mContext = context;
  mCb = c;
  mTypeOfRequest = request;
  mJSONPostData = jsonObj;
  
  //Log.i("JSONDATA", mJSONPostData.toString());
  if((data != null) && (jsonObj == null)){
   mData = data;
   if(mTypeOfRequest.equalsIgnoreCase("GET")){
    Object key = null;
    Iterator<Object> it = mData.keySet().iterator();
    while(it.hasNext()){
     key = it.next();
     mParams.put(key, mData.get(key));
    }
    for (int i = 0; i<mParams.size()-1; i++){
     mStrToBeAppended+= "?" + key + "=" + mParams.get(key) + "&"; 
    }
    //add the last parameter without the "&"
    mStrToBeAppended+= "?" + key + "=" + mParams.get(key);
    
   }
   
   if(mTypeOfRequest.equalsIgnoreCase("POST")){
     Object key = null;
     isPostDataInJSONFormat = false;
     Iterator<Object> it = mData.keySet().iterator();
     while(it.hasNext()){
      key = it.next();
      mParams.put(key, mData.get(key));
     }
   }
  
  }
  if ((mData == null) && (mJSONPostData != null) && (mTypeOfRequest.equalsIgnoreCase("POST") == true)){
   isPostDataInJSONFormat = true;
   //Log.i("ISJSONDATA",Boolean.toString(isPostDataInJSONFormat) );
  }
  
 }
 
 
 
    @Override
    protected String doInBackground(String... baseUrls) {
     
     //android.os.Debug.waitForDebugger();
     
     publishProgress(null);
     if(mTypeOfRequest.equalsIgnoreCase("GET")){
      String finalURL = baseUrls[0]+ mStrToBeAppended;
       return HttpUtility.GET(finalURL);
     }
     
     if (mTypeOfRequest.equalsIgnoreCase("POST")){
      if(isPostDataInJSONFormat == false){
       return HttpUtility.POST(baseUrls[0],mParams );
      }
      if(isPostDataInJSONFormat == true){
       Log.i("JSONDATAPOSTMETHOd","JSON POST method to be called...");
       return HttpUtility.POST(baseUrls[0], mJSONPostData);
      }
     
     }
     
     return null;
    
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
     //if(mContext != null){
      mCb.onResult(result);
     //}
       
       
       
   }
    
    @Override
    protected void onProgressUpdate(Void...voids ) {
     //if(mContext != null){
      mCb.onProgress();
     //}
        
   }
}

The HttpUtility Class


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.util.Log;

public class HttpUtility {
 
 private final static HttpClient mHhttpclient = new DefaultHttpClient();
 
 public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {
 
            // create HttpClient
            //HttpClient httpclient = new DefaultHttpClient();
 
            // make GET request to the given URL
            HttpResponse httpResponse = mHhttpclient.execute(new HttpGet(url));
 
            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
 
            // convert inputstream to string
            if(inputStream != null){
             result = convertInputStreamToString(inputStream);
             //inputStream.close();
            }
                
            else
                result = "Did not work!";
 
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
 
        return result;
    }
 
 public static String POST(String url, HashMap&lt;Object, Object&gt; mParams){
  InputStream inputStream = null;
        String result = "";
  try{
   //HttpClient httpclient = new DefaultHttpClient();
         HttpPost post = new HttpPost(url);
         post.setEntity(new UrlEncodedFormEntity((List extends NameValuePair&gt;) mParams, "UTF-8"));
         HttpResponse httpResponse = mHhttpclient.execute(post);
         
      // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
 
            // convert inputstream to string
            if(inputStream != null){
             result = convertInputStreamToString(inputStream);
             //inputStream.close();
            }
                
            else
                result = "Did not work!";
 
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
 
        return result;
  
        
 }
 public static String POST(String url, JSONObject obj){
  
  Log.i("JSONPOSTBEGIN", "Beginning of JSON POST");
  InputStream inputStream = null;
        String result = "";
     
     //HttpClient httpclient = new DefaultHttpClient();

     try{
      HttpPost post = new HttpPost(url);
      post.setHeader("Content-type", "application/json");
      post.setHeader("Accept", "application/json");
      
      StringEntity se = new StringEntity(obj.toString());
      //se.setContentType("application/json;charset=UTF-8");
         se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
         post.setEntity(se);
         
         HttpResponse httpResponse = mHhttpclient.execute(post);
         
         // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
      
            // convert inputstream to string
            if(inputStream != null){
             result = convertInputStreamToString(inputStream);
            }
                
            else
                result = "Did not work!";
 
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
     Log.i("JSONPOSTEND", "End of JSON data post methos...");
     return result;
 }
 
 public static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;
 
        inputStream.close();
        return result;
 
    }
}

The CallBack Interface


public interface CallBack {
 public void onProgress();
 public void onResult(String result);
 public void onCancel();
}

The callback interface has to be implemented in the Activity from where the Asynctask is called as the following


final CallBack cb = new CallBack(){
   @Override
   public void onProgress() {
    // TODO Auto-generated method stub
    mProgressDialogSignup.show();
   }

   @Override
   public void onResult(String result) {
    // TODO Auto-generated method stub
    
    mProgressDialogSignup.dismiss();
    mStrResult = result;
    //Now process the result 
   }

   @Override
   public void onCancel() {
    // TODO Auto-generated method stub
    
   }
  };

The way these Asynctasks are called are as follows:

String url=  "Your URL"
JSONObject postData = new JSONObject();

postData.put(Key1, Data1);
postData.put(Key2, Data2);

HTTPAsyncTask asyncTask = new AsyncTask(mContext,cb, null, postData, "POST");

asyncTask.execute(url);

Hope this helps the Android learners...

Monday, February 24, 2014

Structural Relationship between Content Resolver and Content Provider - an example of Proxy Design Pattern...

As i was digging into the source code of Content Provider and Content Resolver, i found a nice structural relationship among the two and it closely resembles the Proxy Pattern of the GoF book. We need Proxy Pattern whenever there is a need of a sophisticated reference to an object other than the simple pointer.


The class diagram of the Proxy Pattern is something similar to the following:





What it actually does is that it adds a level of indirection when accessing an object. Whenever a client needs to interact with an object of a RealSubject, it instead interacts with a Proxy of it. The proxy forwards the request to the RealSubject.


Now let us dig into the source code of Content Resolver and Content Provider to understand how it resembles the Proxy Pattern. The Content Provider offers the client of it all of the CRUD (create, read, update & delete) functionalities. Internally what it does it forwards these functionalities to the Content Provider. There is an one to one mapping between the CRUD functions of the Content Resolver with the Content Providers. A simplistic version of the structural relationship between the Content Resolver and the Content Provider can be depicted as follows.



Whenever the client calls any of the above functions on the ContentResolver, it just gets a reference to the appropriate Content Provider by the function called aquireProvider and then delegates that function to that of the ContentProvider. In each of these CRUD functions, the ContentResolver also manages the lifecycle of the ContentProvider it acquires through a function called releaseProvider.


Thus we can say that to a client, the ContentResolver works as a proxy of ContentProviders.

Monday, February 17, 2014

Question Bank for Advanced Android Learners...

I am trying to create a question bank for advanced android learners. You can find it at

http://www.classmarker.com/online-test/start/?quiz=mhy52fd5f7c711fa

Please send me more relevant questions which i can add to this list.

I hope this will give clue to many Android learners to explore more and Google different topics. 

Share