I developed an Android PhoneGap Plugin. The plugin is successfully getting called, but the callback is not getting invoked. I have no idea where I have missed anything.
Does anybody have any idea as to what could be wrong when the callback are not getting invoked?
Following is my code:
JS File Contents:
var SharedPreferencePlugin = function() {};
SharedPreferencePlugin.prototype.getvalues = function(content, success, fail) {
return PhoneGap.exec(
function(args) {
console.log("success called from plugin's js file");
},
function(args) {
console.log("failure called from plugin's js file");
},
'SharedPreferencePlugin',
'getvalues',
[content]
);
};
SharedPreferencePlugin.prototype.update = function(itemName, success, fail) {
return PhoneGap.exec(
function(args) {
console.log("success called from plugin's js file");
},
function(args) {
console.log("failure called from plugin's js file");
},
'SharedPreferencePlugin',
'update',
[itemName]
);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('SharedPreferencePlugin', new SharedPreferencePlugin());
});
Java file:
public class SharedPreferencePlugin extends Plugin{
public static final String GET_ACTION = "getvalues";
public static final String UPDATE_ACTION = "update";
static Context staticContext = MainActivity.staticContext;
SharedPreferences dataStorage = staticContext.getSharedPreferences(MainActivity.PREFS_NAME, 0);
public PluginResult execute(String action, JSONArray data, String callbackId)
{
Log.d("SharedPreferencePlugin", "Plugin Called with action: " + action);
PluginResult result = null;
if(action.equals(GET_ACTION))
{
Log.d("SharedPrferencePlugin", "inside if for 'getvalues'");
JSONArray savedData = getPreferences();
Log.d("SharedPreferencePlugin", "Data: " + savedData);
result = new PluginResult(Status.OK, savedData);
}
else if(action.equals(UPDATE_ACTION))
{
try
{
updateSharedPreferences(data.getJSONObject(0).getString("itemName"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("status", "success");
result = new PluginResult(PluginResult.Status.OK, jsonObject);
}
catch(JSONException ex)
{
Log.d("SharedPreferencePlugin", "Got JSONException: " + ex.getMessage());
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
else
{
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
Log.d("SharedPreferencePlugin", "Invalid action: " + action + " obtained.");
}
return result;
}
public void updateSharedPreferences(String itemName)
{
Log.d("SharedPreferencePlugin", "Inside updateSharedPreferences, value passed: " + itemName);
SharedPreferences tmpPreferenceReference = staticContext.getSharedPreferences(MainActivity.PREFS_NAME, 0);
SharedPreferences.Editor editor = tmpPreferenceReference.edit();
if(itemName.equals(tmpPreferenceReference.getString(MainActivity.NAME_ITEM1, "")))
{
Integer tmpInt = Integer.parseInt(tmpPreferenceReference.getString(MainActivity.QUANTITY_ITEM1, "0")) - 1;
editor.putString(MainActivity.QUANTITY_ITEM1, tmpInt.toString());
}
editor.commit();
}
protected JSONArray getPreferences()
{
ArrayList<String> arrItemNames = new ArrayList<String>();
ArrayList<String> arrItemQuantities = new ArrayList<String>();
arrItemNames.add(0, dataStorage.getString(MainActivity.NAME_ITEM1, ""));
arrItemNames.add(1, dataStorage.getString(MainActivity.NAME_ITEM2, ""));
arrItemQuantities.add(0, dataStorage.getString(MainActivity.QUANTITY_ITEM1, ""));
arrItemQuantities.add(0, dataStorage.getString(MainActivity.QUANTITY_ITEM2, ""));
//-------------------------------------------------------------------
ArrayList<ArrayList> tempArrayList = new ArrayList<ArrayList>();
tempArrayList.add(arrItemNames);
tempArrayList.add(arrItemQuantities);
JSONArray jsonData = new JSONArray(tempArrayList);
//-------------------------------------------------------------------
return jsonData;
}
}
HTML CODE TO CALL THE PLUGIN:
function test()
{
console.log("Test called");
window.plugins.SharedPreferencePlugin.getvalues({},
function() { // Success function
console.log("success called");
},
function() { // Failure function
console.log('Share failed');
}
);
}
Any help is highly appreciated.
Thanks.
When you say it is definitely running the native code, how do you know this? Are you seeing the Log.d's or are you actually putting a break point in and stepping through and seeing if the return result; line is being executed?
Also, which version of phonegap are you using?
If you are using PhoneGap 1.2 you should remove the line:
PluginManager.addService("SharedPreferencePlugin","com.devapps.mmvspinningwheel.SharedPreferencePlugin");
as it is not required. Also, you should probably move PhoneGap.addConstructor() to the bottom of your .js file.
Dean is not wrong as there are some devices like the HTC that console.log does not work properly on, as well what version of Android are you testing with?
Thank you guys for your answers.
Since the problem was not getting solved, I recreated a new Test project and went step by step to ensure that each little piece of code works properly and slowly moved to the desired goal for the plugin.
I finally got it working with the new project I created and writing the Plugin again from scratch.
Thanks.
Related
How can I send HTTP GET and POST requests in C# with Unity?
What I want is:
send json data in post request (I use Unity serializer, so no need in
new one, I just want to pass string in post data and have ability to
set ContentType to application/json);
get response code and body without any problems;
do it all asynchronous without blocking ui rendering.
What I've tried:
implementing with HttpWebRequest/HttpWebResponse, but it's too hard and low level (if I won't found anything better, I'll have to use it);
using unity WWW, but it doesn't match my requirements;
using some external packages from NuGet - Unity don't accept them :(
Most problems were with threading, I'm not experienced enough in it in C#.
IDE, I use, is Intellij Rider.
The WWW API should get this done but UnityWebRequest replaced it so I will answer the newer API. It's really simple. You have to use coroutine to do this with Unity's API otherwise you have have to use one of C# standard web request API and Thread. With coroutine you can yield the request until it is done. This will not block the main Thread or prevent other scripts from running.
Note:
For the examples below, if you are using anything below Unity 2017.2, replace SendWebRequest() with Send() and then replace isNetworkError with isError. This will then work for the lower version of Unity. Also, if you need to access the downloaded data in a binary form instead, replace uwr.downloadHandler.text with uwr.downloadHandler.data. Finally, the SetRequestHeader function is used to set the header of the request.
GET request:
void Start()
{
StartCoroutine(getRequest("http:///www.yoururl.com"));
}
IEnumerator getRequest(string uri)
{
UnityWebRequest uwr = UnityWebRequest.Get(uri);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
POST request with Form:
void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com"));
}
IEnumerator postRequest(string url)
{
WWWForm form = new WWWForm();
form.AddField("myField", "myData");
form.AddField("Game Name", "Mario Kart");
UnityWebRequest uwr = UnityWebRequest.Post(url, form);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
POST request with Json:
void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com", "your json"));
}
IEnumerator postRequest(string url, string json)
{
var uwr = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
uwr.SetRequestHeader("Content-Type", "application/json");
//Send the request then wait here until it returns
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
POST request with Multipart FormData/Multipart Form File:
void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com"));
}
IEnumerator postRequest(string url)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("field1=foo&field2=bar"));
formData.Add(new MultipartFormFileSection("my file data", "myfile.txt"));
UnityWebRequest uwr = UnityWebRequest.Post(url, formData);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
PUT request:
void Start()
{
StartCoroutine(putRequest("http:///www.yoururl.com"));
}
IEnumerator putRequest(string url)
{
byte[] dataToPut = System.Text.Encoding.UTF8.GetBytes("Hello, This is a test");
UnityWebRequest uwr = UnityWebRequest.Put(url, dataToPut);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
DELETE request:
void Start()
{
StartCoroutine(deleteRequest("http:///www.yoururl.com"));
}
IEnumerator deleteRequest(string url)
{
UnityWebRequest uwr = UnityWebRequest.Delete(url);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Deleted");
}
}
Use HttpClient and something like:
public static HttpContent DoPost(object payload, string subPath)
{
var httpClient = new HttpClient();
HttpClient.BaseAddress = new Uri(Global.BaseUrl);
HttpClient.DefaultRequestHeaders.Clear();
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // if you're using json service
// make request
var response = Global.HttpClient.PostAsJsonAsync(subPath.TrimLeadingSlash(), payload).Result;
// check for error
response.EnsureSuccessStatusCode();
// return result
return response.Content;
}
Payload is an object to be serialized to json. If all requests are going to the same baseUrl, you can set up HttpClient globally, and reuse it here
https://www.patrykgalach.com/2019/04/18/how-to-call-rest-api-in-unity/
Please refer this link cleanest way to play with data
and do not use www instead of use UnityWebRequest
We can use WWW and UnityWebRequest classes to initiate API calls. WWW got obsolete now and Unity recommends using UnityWebRequest over WWW.
void Start() {
string url = "https://retrofit-backend-demo.herokuapp.com/book";
StartCoroutine(GetBooksUsingWWW(url));
StartCoroutine(GetBooksUsingUnityWebRequest(url));
}
IEnumerator GetBooksUsingWWW(string url) {
using (WWW www = new WWW(url)){
yield return www;
Debug.Log(www.text);
JSONNode jsonNode = JSON.Parse(www.text);
string title = jsonNode[0]["title"].ToString();
Debug.Log("Title: " + title);
}
}
IEnumerator GetBooksUsingUnityWebRequest(string url) {
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
Debug.Log(www.downloadHandler.text);
JSONNode jsonNode = JSON.Parse(www.downloadHandler.text);
string title = jsonNode[0]["title"].ToString();
Debug.Log("Title: " + title);
}
}
For demo: https://github.com/codemaker2015/api-interaction-unity3d-demo
I have some pics to upload to the ftp server and I am using Asynctask for it.The images need to be sent to multiple host so I am using a for loop.The data to be passed is very well being fetched by the constructor but the doInBackground method is not running which was earlier running very well without the for loop and the additional data apart from the String filePathName that I am trying to pass in now in doInBackground.please help me
class uploadTask extends AsyncTask<String, Void, String> {
public uploadTask(String filePathName,String host_2,String user_2,String pass_2)
{
filePath=filePathName;
host_1=host_2;
user_1=user_2;
pass_1=pass_2;
Toast.makeText(getBaseContext(),"FTP DATA RECEIVING:"+"HOST:"+host_2+" USERNAME:"+user_2+" PASS:"+pass_2,Toast.LENGTH_LONG).show();
//hostName=host;
}
#Override
protected String doInBackground(String... params) {
try {
Toast.makeText(getBaseContext(),"Entered Do in Background Method to upload",Toast.LENGTH_SHORT).show();
ftp_host = "ftp.photoshelter.com";//This is not the correct way. Supposed to get from Backendless table
ftp_username = "brytest";//This is not the correct way. Supposed to get from Backendless table
ftp_password = "passtest";//This is not the correct way. Supposed to get from Backendless table
Toast.makeText(getBaseContext(),"HOST:"+ftp_host+" USERNAME:"+ftp_username+" PASS:"+ftp_password,Toast.LENGTH_LONG).show();
news_agency = "news agency";
easyFTP ftp = new easyFTP();
ftp.connect(ftp_host, ftp_username, ftp_password);
status = ftp.setWorkingDirectory("mem/images"); // if User say provided any Destination then Set it , otherwise
// Upload will be stored on Default /root level on server
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageTimeStamped = ftp_username + "_" + timeStamp + ".png";
FileInputStream is = new FileInputStream(imageFileLocation);
//addPhotoGrapherInfo();
ftp.uploadFile(is, imageTimeStamped);
System.out.println("Successfull ftp upload to " + ftp_host);
Toast.makeText(getBaseContext(), "Photo uploading by ftp to " + ftp_host, Toast.LENGTH_LONG).show();
//}
//reset booleans
//cameraPicTaken = false;
//galleryImageSelected = false;
//System.out.println("reset cameraPicTaken and galleryImageSelected");
// }
return new String("Upload Successful");
}catch (Exception e){
String t="Failure : " + e.getLocalizedMessage();
return t;
}
}
}
my onClickListener with for loop
if(cameraPicTaken || galleryImageSelected) {
Toast.makeText(SubmitActivity.this,"Image Location is:"+ imageFileLocation,Toast.LENGTH_LONG).show();
//addPhotoGrapherInfo();
for(int i=0;i<Common.selectedHostArray.size();i++) {
uploadFile(imageFileLocation,Common.selectedHostArray.get(i),Common.selectedUsernameArray.get(i),Common.selectedPasswordArray.get(i));
}
cameraPicTaken = false;
galleryImageSelected = false;
}
funnction called in onClick
public void uploadFile(String filePath,String host_1,String user_1,String pass_1)
{
if(cameraPicTaken == true) {
System.out.println("camera photo start upload");
//for(int i=0;i<Common.selectedHostArray.size();i++) {
//host_1=Common.selectedHostArray.get(i);
//user_1=Common.selectedUsernameArray.get(i);
//pass_1=Common.selectedPasswordArray.get(i);
//host_1="ftp.photoshelter.com";
//user_1="brytest";
//pass_1="passtest";
Toast.makeText(getBaseContext(),"FTP DATA PASSING:"+"HOST:"+host_1+" USERNAME:"+user_1+" PASS:"+pass_1,Toast.LENGTH_LONG).show();
new uploadTask(filePath,host_1,user_1,pass_1).execute();
// }
//cameraPicTaken = false;
//galleryImageSelected = false;
System.out.println("reset cameraPicTaken and galleryImageSelected");
//cameraPicTaken = false;
}
if(galleryImageSelected == true){
System.out.println("gallery image start upload");
Toast.makeText(getBaseContext(),"FTP DATA PASSING:"+"HOST:"+host_1+" USERNAME:"+user_1+" PASS:"+pass_1,Toast.LENGTH_LONG).show();
new uploadTask(filePath,host_1,user_1,pass_1).execute();
//new uploadTask(filePat)h.execute();
//galleryImageSelected = false;
}
Toast.makeText(getBaseContext(), "Photo uploading by ftp to photoshelter.com" /*+ news_agency*/, Toast.LENGTH_LONG).show();
}
You're trying to perform a UI command on a background thread (Toast). This is causing your background tasks to fail early. Since your background tasks catch their own errors, they fail silently.
#Override
protected String doInBackground(String... params) {
try {
// you can't Toast on a background thread, this should throw an exception
Toast.makeText(getBaseContext(),"Entered Do in Background Method to upload",Toast.LENGTH_SHORT).show();
...
}catch (Exception e){
// your Toast exception is getting caught silently here
String t="Failure : " + e.getLocalizedMessage();
return t;
}
}
By the way, the try/catch on everything is not a good practice. You end up with a ton of silent failures leaving you scratching your head and asking why things aren't working.
I'm trying to upload multiple images to a PHP server along with a few other parameters (strings), using the POST method. I'm using Multipart method. I added 4 libraries prescribed in various solutions (apachemime, httpclient, httpmime, httpcore), but my SDK doesn't recognise MultipartEntity, displaying the error: 'cannot be resolved to a type'. I've also tried MultipartEntityBuilder, but even that's showing the same error. I basically want to upload a Bitmap Arraylist to the server & show a progress bar simultaneously.
You should post some code with the issue so we can take a look and help you.
But if you want to try something a little bit simple you can use this library, AsyncHttpClient: http://loopj.com/android-async-http/
Using this library you could post multiple files like this:
private static AsyncHttpClient clientHttp = new AsyncHttpClient();
...
RequestParams params = new RequestParams();
final String TAG_FILE = "archivo1";
final String TAG_FILE_1 = "archivo2";
final String TAG_FILE_2 = "archivo3";
final String PATH_FILE_1 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file1.jpg";
final String PATH_FILE_2 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file2.jpg";
final String PATH_FILE_3 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file3.jpg";
try {
params.put(TAG_FILE, PATH_FILE_1);
params.put(TAG_FILE_1, PATH_FILE_2);
params.put(TAG_FILE_2, PATH_FILE_3);
params.put(TAG_PARAM, "SOME TEXT");
}
catch(FileNotFoundException e) {
//Manage your exception
}
final int DEFAULT_TIMEOUT = 30 * 1000;
clientHttp.setTimeout(DEFAULT_TIMEOUT);
clientHttp.post("http://somereceiver.php", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
//Do your code on success
}
#Override
public void onStart() {
// Show your progress bar
}
#Override
public void onFinish() {
// Hide your progress bar
super.onFinish();
if(PATH_FILE_1 != null) {
File tem = new File(PATH_FILE_1);
if(tem.exists()) tem.delete();
}
if(PATH_FILE_2 != null) {
File tem = new File(PATH_FILE_2);
if(tem.exists()) tem.delete();
}
if(PATH_FILE_3 != null) {
File tem = new File(PATH_FILE_3);
if(tem.exists()) tem.delete();
}
}
});
You could also use the generic response type if you dont need json, so you get a string.
Hope this helps.
After making a call to the "me/home" Graph API, while parsing the JSON result, I am trying to make another query using FQL. The FQL query problem was solved in my earlier question.
The background of my implementation is: I am using a BaseAdapter and from the main activity, I am sending the data parsed from JSON using multiple ArrayLists. If I am not making the FQL query, everything is peachy. But when I introduce the FQL query, the query is always run after the adapter has been set to the ListView. This keeps causing the arrayindexoutofbound exception.
This is the code that I am using including the additional FQL query while parsing the JSON result. To keep the code short, I will include the relevant part as the rest works just fine. If more is needed, however, I will put that up too.
// GET THE POST'S LIKES COUNT
if (json_data.has("likes")) {
JSONObject feedLikes = json_data.optJSONObject("likes");
String countLikes = feedLikes.getString("count");
postLikesCountArrayList.add(countLikes);
// TEST STARTS
Runnable run = new Runnable() {
#Override
public void run() {
graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'"
+ finalThreadID + "\'";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
Utility.mAsyncRunner.request(null, params, new LikesListener());
}
};
TestNewsFeeds.this.runOnUiThread(run);
// TEST ENDS
} else {
String countLikes = "0";
postLikesCountArrayList.add(countLikes);
}
And this is the code for the LikesListener class. It is a private class declared in the same activity:
private class LikesListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
// Log.e("response", response);
try {
JSONArray JALikes = new JSONArray(response);
// Log.v("JALikes", JALikes.toString());
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
// Log.e("JOTemp", JOTemp.toString());
if (JOTemp.has("likes")) {
JSONObject optJson = JOTemp.optJSONObject("likes");
// Log.v("optJson", optJson.toString());
if (optJson.has("user_likes")) {
String getUserLikeStatus = optJson.getString("user_likes");
Log.e("getUserLikeStatus", getUserLikeStatus);
arrayLikeStatus.add(getUserLikeStatus);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have figured out using debugging that the cause of the crash is the setAdapter being called before the second query completes. I see the log's being added to logcat after the crash has occured.
Any help on a solution for this is appreciated
UPDATE: Figured out the solution almost when I was about to give up.
SOLUTION
So instead of calling the BaseRequestListener as used in the question, this modification had to be made.
try {
graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'"
+ finalThreadID + "\'";
// Log.d("finalThreadID", finalThreadID);
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
// Utility.mAsyncRunner.request(null, params, new LikesListener());
String fqlResponse = Utility.mFacebook.request(params);
// Log.e("fqlResponse", fqlResponse);
JSONArray JALikes = new JSONArray(fqlResponse);
// Log.v("JALikes", JALikes.toString());
for (int j = 0; j < JALikes.length(); j++) {
JSONObject JOTemp = JALikes.getJSONObject(j);
// Log.e("JOTemp", JOTemp.toString());
if (JOTemp.has("likes")) {
JSONObject optJson = JOTemp.optJSONObject("likes");
// Log.v("optJson", optJson.toString());
if (optJson.has("user_likes")) {
String getUserLikeStatus = optJson.getString("user_likes");
// Log.e("getUserLikeStatus", getUserLikeStatus);
arrayLikeStatus.add(getUserLikeStatus);
// Log.d("arrayLikeStatus", arrayLikeStatus.toString());
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
Hope this helps someone save time if they are stuck like I was.
I am new to android phonegap. i am storing and retrieving data using native application. i dont know how to display the retrieved data from native to phonegap(HTML)page.
can anyone pls guide me how to access sqlite with phonegap.?
Thanks in advance.
You need to first create a Android plugin for Phonegap through which you will be able to access the native code and hence the native DB like this
public class SqlitePlugin extends Plugin {
private static final String TAG = "SqlitePlugin";
private static final String CREATE_DB_ACTION = "createDatabase";
private static final String SHOW_DB_VALUES_ACTION = "showValues";
#Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
Log.i(TAG, "Plugin Called");
PluginResult result = null;
if (CREATE_DB_ACTION.equals(action)) {
Log.d(TAG, "CREATE_DB_ACTION");
DB _db = new DB(ctx);
_db.insertValues();
}
else if (SHOW_DB_VALUES_ACTION.equals(action)) {
Log.d(TAG, "SHOW_DB_VALUES_ACTION");
JSONObject DBInfo = null;
try {
DBInfo = getDBValuesListing();
} catch (JSONException e) {
e.printStackTrace();
}
result = new PluginResult(Status.OK, DBInfo);
}
else {
result = new PluginResult(Status.INVALID_ACTION);
Log.d(TAG, "Invalid action : " + action + " passed");
}
return result;
}
}
After that Create a sqlite.js file like this
function SqlitePlugin() {
};
SqlitePlugin.prototype.createDatabase = function(successCallback, failCallback) {
return PhoneGap.exec(successCallback, failCallback, "SqlitePlugin",
"createDatabase", [ null ]);
};
SqlitePlugin.prototype.showValues = function(params, successCallback, failCallback) {
return PhoneGap.exec(successCallback, failCallback, 'SqlitePlugin', 'showValues',
[ params ]);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin("SqlitePlugin", new SqlitePlugin());
});
Import this sqlite.js in your page(index.html) and then finally use the plugin like this
function showValues() {
window.plugins.SqlitePlugin.showValues('showValues',
showValuesSuccessCallBack, showValuesFailCallBack);
}
function showValuesSuccessCallBack(e) {
if (e.Rows.length > 0) {
alert("Success");
for (i = 0; i < e.Rows.length; i++) {
alert("Id = " + e.Rows[i].id);
alert("Number = " + e.Rows[i].number);
}
} else {
alert("No values in Database");
}
}
function showValuesFailCallBack(f) {
alert("Failure");
}
Let me know if this worked out for you
Write an phonegap plugin to pass the data from native side to html (js)
http://wiki.phonegap.com/w/page/36753494/How%20to%20Create%20a%20PhoneGap%20Plugin%20for%20Android
Well, you probably should use the HTML5 functions to store and retrieve data from a sqlite DB. However, if you are set on doing it with native code you should look at our implementation which was used for older Android devices that don't support sqlite.
https://github.com/cordova/cordova-android/blob/master/framework/assets/js/storage.js
https://github.com/cordova/cordova-android/blob/master/framework/src/com/phonegap/Storage.java