Friday, May 17, 2013

PhoneGap Android Plugin creation and Calling from HTML page

If we want Call Android Activity from Java Script  while Using PhoneGap.In this Scenario you need One Phone Gap Plugin.

 Here i explain In details How to Start and Implementation.


HTML Page:
-------------


<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/cordova-2.0.0.js"></script> 
<script type="text/javascript">

function callPlugin()
{
HelloPlugin.callNativeFunction( nativePluginResultHandler, nativePluginErrorHandler,text); 
}

var HelloPlugin = { 
    callNativeFunction: function (success, fail, resultType) { 
    return cordova.exec( success, fail, "HelloPlugin",  "nativeAction", [resultType]); 
//In the above method "HelloPlugin" very Usefull.Its refer to The our Plugin class.This parameter are used in //cordova.xml or plugin.xml file
//"nativeAction" is Action name its used in Plugin
//"resultType" is Responce vlaues.
    } 
};

//This Method Executes after  Success 
function nativePluginResultHandler (result) { 

//This method executes if any error occured while executing the plugin.
function nativePluginErrorHandler (error) { 
</script>
</head>
<body>
 <form>
<input type="button" value="Call PhoneGap Plugin" onClick="callPlugin()"/>
</form>
</body>
</html>


XML FILE:
-----------

In res/xml folder have the xml files. Here you integrate your plugin class and Reference of the plugin class (Declared in javascript function cordova.exec( success, fail, "HelloPlugin",  "nativeAction", [resultType]);)

config.xml:
=======
you create one more plugin tag here
 <plugin name="HelloPlugin" value="com.test.plugin..HelloPlugin"/> //colored thing is your plugin class


Plugin class:
-----------


package com.test.plugin;

import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.util.Log;


public class HelloPlugin extends Plugin { 
public static final String NATIVE_ACTION_STRING="nativeAction"; 
      public static final String SUCCESS_PARAMETER="success"; 
      @Override 
      public PluginResult execute(String action, JSONArray data, String callbackId) { 
             Log.d("HelloPlugin", "Hello, this is a native function called from PhoneGap/Cordova!"); 
             //only perform the action if it is the one that should be invoked 
             if (NATIVE_ACTION_STRING.equals(action)) { 
             
            Intent ie = null;
            String buy_data = null;
           
                      try {
                     buy_data=data.getString(0);
                      }
                      catch (JSONException e) {
e.printStackTrace();
                      }
                  
                  
             } 
             return null; 
      } 


Now its working fine

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;

}

}

}