Thursday, May 16, 2013

Calling Rest Full Services from Android Activity


  If you want to call Rest Service from Android Activity.It is very Simple you just Integrated one class like LongRunningGetIO  .it will be execute and return responce to your Class


package com.asman;
public class RestServiceActivity extends DroidGap {
Context context = this.getContext();
private String android_id;

private String SERVER;
String valid_type;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splashscreen);
android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);

SERVER = "http://<Your HostName>/sample/";

try {
new LongRunningGetIO().execute();
Thread.sleep(1000);
} catch (Exception e) {
}
if(valid_type.equalsIgnoreCase("valid")||valid_type=="valid")
{
super.loadUrl("file:///android_asset/www/index.html", 5000);
}
}

protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}


/**

  This Class used to call the Rest Services.
*/
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {

protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}

@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();

String text = null;



//This is Your Service URL
String urlString = SERVER + "userplans/validateUser?userdetail_id=44";
                     
                       //Calling The Service
HttpGet httpGet = new HttpGet(urlString);


try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);

                          //text Contains JSON Responce data.
Log.v("response is from server .......", text);

} catch (ClientProtocolException e) {
System.out.println("error " + e.getLocalizedMessage());
Log.v("error is.....", e.getLocalizedMessage());
} catch (IOException e) {
Log.v("error is.....", e.getLocalizedMessage());
return e.getLocalizedMessage();
}

return valid_type;

}

}

}

No comments:

Post a Comment