Friday, 14 June 2013

Call REST webservices with header parameter in android async task

1.Async task 

public static class CurrentUserTask extends AsyncTask<Void, Void, Object> {
private String TAG = "User Profile";
private UserListener userListener;
private Context context;

public CurrentUserTask(Context context, UserListener listener) {
this.context = context;
this.userListener = listener;
}

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Object doInBackground(Void... params) {

try {

//Create constants for URL and content type 


HttpGet httpGet = new HttpGet(Constants.BASE_URL
+ Constants.USER_URL);
Log.d(TAG, "Profile URL" + Constants.BASE_URL
+ Constants.USER_URL);

httpGet.setHeader(Constants.CONTENT_TYPE,
Constants.CONTENT_TYPE_JSON);
httpGet.setHeader(Constants.AUTHORIZATION,
PreferenceManager.getAuthorization(context));

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);

String response = IOUtils.streamToString(httpResponse
.getEntity().getContent(), null);
Log.d(TAG, "response:" + response);
switch (httpResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
Gson gson = new Gson();
JSONObject jsonObject = new JSONObject(response);
Profile contact = gson.fromJson(jsonObject.toString(),
Profile.class);
PreferenceManager.setCurrentUser(context, response);
return contact;

case HttpStatus.SC_INTERNAL_SERVER_ERROR:
return null;
case HttpStatus.SC_UNAUTHORIZED:
return null;
default:
return null;
}

} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
return null;
} catch (ClientProtocolException ex) {
ex.printStackTrace();
return null;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}

@Override
protected void onPostExecute(Object contact) {
super.onPostExecute(contact);
try {
if (contact == null)
userListener.onError();
else {
userListener.onSuccess((Profile) contact);
}
} catch (Exception e) {
e.printStackTrace();
userListener.onError();
}
}

}


2.Create pojo class for Profile (entity class)
 with getter and setter methods

eg.
public class Profile implements Serializable {

private static final long serialVersionUID = 1L;
private String email;
private String dateOfBirth;

//getter and setter methods here......

}

3.Custom error message class 

public class ErrorMessages extends Exception {

public ErrorMessages(String message) {
super(message);
}

public static String MESSAGE_NETWORK="Please check network connection.";
public static String MESSAGE_INTERNAL_SERVER_ERROR="Error occurred at server, please try again.";
}


4.static method to convert stream to string. 


public static String streamToString(InputStream is, Charset cs)
throws IOException, Exception {
BufferedReader br;
if (cs == null) {
br = new BufferedReader(new InputStreamReader(is));
} else {
br = new BufferedReader(new InputStreamReader(is, cs));
}
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}

5.Custom interface to handel response call back

public static interface UserListener {
public void onSuccess(Profile profile);

public void onUnauthorized();

public void onError();
}

6.call sync task into activity

//show progress dialog here... 

new UserTask.CurrentUserTask(context, userListener).execute();

//call back method into activity (methods of Interface)


/**
* current user listener
*/

UserListener userListener = new UserListener() {

@Override
public void onUnauthorized() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();

Toast.makeText(context, R.string.msg_error, Toast.LENGTH_SHORT)
.show();
}

@Override
public void onSuccess(Profile profile) {

if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();

//Success 

}

@Override
public void onError() {
Log.d(TAG, "userListener on error");
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
};

Splash activity or Welcome page in android

public class SplashActivity extends Activity {
private long time = 2000; //time
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);

Handler handler = new Handler();

// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {

@Override
public void run() {
finish();
Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
}

}, time);
}

}