Populated Sqlite DB with Phonegap for Android - android

I have been trying to populate SQLite DB with phonegap for Android.I am following this post. I have been able to follow the first two steps i.e using this plugin.
My question is:
1) When i was able to populate a database by following 1st step, Why should i follow the second and third steps?
2) Following third step, I ended up in dilemma as i dint find any file named "0000000000000001.db" in data > data > [MY APP NAME] > app_database. And my Database.db is in
data > data > [MY APP NAME] > databases.
my index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Minimal AppLaud App</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
<script type="text/javascript" charset="utf-8" src="SQLitePlugin.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table
(id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)",
["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
alert("insertId: " + res.insertId + " -- should be valid");
db.transaction(function(tx) {
tx.executeSql("SELECT data_num from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
alert("res.rows.length: " + res.rows.length + " -- should be 1");
alert("res.rows.item(0).data_num: " + res.rows.item(0).data_num + "should be 100");
});
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}
</script>
</head>
<body onload="init();" id="stage" class="theme">
<p>Your app goes here.</p>
</body>
</html>
MyPhonegapActivity.java
package org.mobinius.sqltry1;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import java.io.*;
import android.app.Activity;
import android.view.Menu;
public class MyPhoneGapActivity extends DroidGap {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
String pName = this.getClass().getPackage().getName();
this.copy("Database.db","/data/data/"+pName+"/databases/");
//this.copy("0000000000000001.db","/data/data/"+pName+"/app_database/file__0/");
}
catch (IOException e)
{
e.printStackTrace();
}
super.loadUrl("file:///android_asset/www/index.html");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
void copy(String file, String folder) throws IOException {
File CheckDirectory;
CheckDirectory = new File(folder);
if (!CheckDirectory.exists())
{
CheckDirectory.mkdir();
}
InputStream in = getApplicationContext().getAssets().open(file);
OutputStream out = new FileOutputStream(folder+file);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
in.close(); out.close();
}
}
As you can see in screen shot there is no db file named "0000000000000001.db". Please help me on this.

Related

PHONEGAP how can i build my application including the database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
hi i am new to phonegap .. i try using phonegap with database now, i am able to display the records in emulator / fetch record .. but when i try to build the application in build.phonegap.com to make .apk when i install the application and run in my android no record display .. my question is how can i build my application including the database ? i have .db already where should i place it or something do i need to add some script ? hope u get my point and sorry for my english..
here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Storage Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
}
function clickFunc(){
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(selectData);
}
function selectData(tx){
tx.executeSql("SELECT * FROM test",[],resultSuccess,resultError);
}
function resultError(error){
alert("Error: "+error);
}
function resultSuccess(tx, response){
var div = document.getElementById('display');
var tmp = "<table><tr><th>ID</th><th>DATA</th></tr>";
for(var i = 0;i<response.rows.length;i++){
tmp += "<tr><td>" + response.rows.item(i).id + "</td><td>" + response.rows.item(i).data + "</td></tr>";
div.innerHTML = tmp;
}
}
</script>
</head>
<body>
<input type="button" value="FITCH" id="btnSelect" onclick="clickFunc();"/>
<div id="display">
</div>
Your create only database but your not create any table and nothing to insert it. So that your apk doesn't produce your excepted result.
So you will try this code
<!DOCTYPE html>
<html>
<head>
<title>Storage Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.4.0.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function clickFunc(){
var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
db.transaction(selectData);
}
function selectData(tx){
tx.executeSql("SELECT * FROM test",[],resultSuccess,resultError);
}
function resultError(error){
alert("Error: "+error);
}
function resultSuccess(tx, response){
var div = document.getElementById('display');
var tmp = "<table><tr><th>ID</th><th>DATA</th></tr>";
for(var i = 0;i<response.rows.length;i++){
tmp += "<tr><td>" + response.rows.item(i).id + "</td><td>" + response.rows.item(i).data + "</td></tr>";
div.innerHTML = tmp;
}
}
</script>
</head>
<body>
<input type="button" value="FITCH" id="btnSelect" onclick="clickFunc();"/>
<div id="display">
</div>
If you need more details please refer this link: http://docs.phonegap.com/en/2.7.0/cordova_storage_storage.md.html#Storage

PhoneGap File Read Write: PhoneGap read write file html code isn't working on android device

I was trying some cookbook samples of phonegap app(along with xui) to read write files to local storage(SD card), PhoneGap is so popular in its file io, but when I tried on the device it didn't do anything. I think somebody has encountered same things.
The code is shown below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
<title>File Download</title>
<script type="text/javascript" src="xui.js"></script>
<script type="text/javascript" src="cordova-2.0.0.js"></script>
<script type="text/javascript" >
var downloadDirectory;
document.addEventListener("deviceready", onDeviceReady, true);
function onDeviceReady() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
onFileSystemSuccess,
null
);
x$('#download_btn').on( 'click', function(e) {
download();
});
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory('my_downloads',{create:true},
function(dir) {
downloadDirectory = dir;
},fail);
}
function fail(error) {
x$('#message').html('We encountered a problem: ' + error.code);
}
function download() {
var fileURL = document.getElementById('file_url').value;
var localFileName = getFilename(fileURL);
x$('#message').html('Downloading ' + localFileName);
var fileTransfer = new FileTransfer();
fileTransfer.download(fileURL, downloadDirectory.fullPath + '/' + localFileName,
function(entry){
x$('#message').html('Download complete. File saved to: ' + entry.fullPath);
},
function(error){
alert("Download error source " + error.source);
}
);
}
// Obtain the filename
function getFilename(url) {
if (url) {
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1) {
return m[1] + '.' + url.split('.').pop();
}
}
return "";
}
</script>
</head>
<body>
<input type="text" id="file_url" value="http://blogs.adobe.com/adobeingovernment/files/2012/07/phonegap.jpg" />
<input type="button" id="download_btn" value="Download" />
<div id="message"></div>
</body>
</html>
I already reviewed android manifest file, it has all permission including write to external storage. Kindly advise.

Phonegap : Upload Failed

Phonegap: 2.9.0
Android: 4.4.2
Device: Nexus 5
I moved the "assets\www" files to my host, and "super.loadUrl("http://mydomain.com");", Because it's easy to maintain, lucky, Phonegap works!
But it can not uploads files, why? Here is my codes:
MainActivity.java
import android.os.Bundle;
import org.apache.cordova.*;
public class MainActivity extends DroidGap
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("http://mydomain.com");
}
}
index.php (on host)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady()
{
console.log("device ready");
// Do cool things here...
}
function getImage()
{
// Retrieve image file location from specified source
navigator.camera.getPicture
(
uploadPhoto,
function(message)
{
alert('get picture failed');
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI)
{
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "upload.php", win, fail, options);
}
function win(r)
{
console.log("Code = " + r.responseCode.toString()+"\n");
console.log("Response = " + r.response.toString()+"\n");
console.log("Sent = " + r.bytesSent.toString()+"\n");
alert("Code Slayer!!!");
}
function fail(error)
{
alert("An error has occurred: Code = " + error.code);
}
</script>
</head>
<body>
<button onclick="location.replace(location.href);">Refresh</button>
<button onclick="getImage();">Upload a Photo</button>
</body>
</html>
</html>
upload.php (on host)
<?php
print_r($_FILES);
?>
I click the button and select a photo, it alerts "An error has occurred.Code = 2", how to solve this problem?
Thanks for help!
You will want to specify a full path to the upload.php file, example:
ft.upload(imageURI, "http://www.mydomain.com/upload.php", win, fail, options);

Download a file from an url into sdk card

I am working on phonegap with android project. i want to download a file from url into my sdk card.
this is my Downloader.java
package com.example.pgplugins.downloaderPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
import com.phonegap.DroidGap;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader extends Plugin{
#Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
if (action.equals("downloadFile")) {
try {
return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
}
}
else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
}
private PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
try{
Log.d("DownloaderPlugin", "DIRECTORY CALLED /sdcard/"+dirName+" created");
File dir = new File("/sdcard/"+dirName);
if(!dir.exists()){
Log.d("DownloaderPlugin", "directory /sdcard/"+dirName+" created");
dir.mkdirs();
}
File file = new File("/sdcard/"+dirName+fileName);
if(overwrite.equals("false") && file.exists()){
Log.d("DownloaderPlugin", "File already exist");
return new PluginResult(PluginResult.Status.OK, "exist");
}
URL url = new URL(fileUrl);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setRequestMethod("GET");
ucon.setDoOutput(true);
ucon.connect();
Log.d("DownloaderPlugin", "download begining");
Log.d("DownloaderPlugin", "download url:" + url);
InputStream is = ucon.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
FileOutputStream fos = new FileOutputStream(file);
while ( (len1 = is.read(buffer)) > 0 ) {
fos.write(buffer,0, len1);
}
fos.close();
Log.d("DownloaderPlugin", "Download complete in" + fileName);
} catch (IOException e) {
Log.d("DownloaderPlugin", "Error: " + e);
return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
}
return new PluginResult(PluginResult.Status.OK, fileName);
}
}
this is my Downloader.js
function Downloader() {
}
Downloader.prototype.downloadFile = function(fileUrl,dirName,fileName,overwrite,win,fail) {
if(overwrite==false) overwrite="false";
else overwrite="true";
PhoneGap.exec(win, fail, "Downloader", "downloadFile", [fileUrl,dirName,fileName,overwrite]);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin("downloader", new Downloader());
PluginManager.addService("Downloader","com.example.pgplugins.downloaderPlugin.Downloader");
});
this is my index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap Demo With JQuery Mobile</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0b2.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="pgandjqm-style-override.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="jquery.mobile/jquery-1.6.2.min"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0b2.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
<!-- CDN Respositories: For production, replace lines above with these uncommented minified versions -->
<!-- <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />-->
<!-- <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>-->
<!-- <script src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>-->
script type="text/javascript" charset="utf-8" src="downloader.js"></script>
<script type="text/javascript">
window.plugins.downloader.downloadFile("http://www.toforge.com/archive.zip","sdcard/cache/","archive.zip", false,
function(data){
if(data=="exist"){
alert("File already exist");
}
else{
alert("File saved on sd card")
}
},function(data){ alert("error: "+data); });
</script>
</head>
<body onload="init();">
</body>
</html>
whenever i run that program, this error occurred, means no result is getting by me.
error:- FORCE TO CLOSE THE PROGRAM.
my program is not running.means before starting the run a halt is occurred. please check my code and help me to find out the error.
If want to download the file in background using the services with notification then please check this out android: file download in background
I hope this will help you.

phonegap download file from url to sdcard

I am working on phonegap with android. i want to download a file from given url to my sd card.
**this is my index.html**
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap Demo With JQuery Mobile</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0b2.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="pgandjqm-style-override.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="jquery.mobile/jquery-1.6.2.min"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0b2.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
<script type="text/javascript" charset="utf-8" src="downloader.js"></script>
<script type="text/javascript">
function down1()
{
window.plugins.downloader.downloadFile("http://192.168.1.214/sample/Winter.jpg","/mnt/sdcard/","archive.zip", false,
function(data){
if(data=="exist")
{
alert("File already exist");
}
else
{
alert("File saved on sd card")
}
},function(data){ alert("error is : "+data); });
}
</script>
</head>
<body>
<div data-role="button" onclick="down1();">Get data</div>
</body>
</html>
**this is my downloader.js**
function Downloader() {
}
Downloader.prototype.downloadFile = function(fileUrl,dirName,fileName,overwrite,win,fail) {
if(overwrite==false) overwrite="false";
else overwrite="true";
PhoneGap.exec(win, fail, "Downloader", "downloadFile", [fileUrl,dirName,fileName,overwrite]);
};
PhoneGap.addConstructor(function() {
console.log('=============i am in addConstructor================');
PhoneGap.addPlugin("downloader", new Downloader());
PluginManager.addService("Downloader","com.example.pgplugins.DownloaderPlugin");
});
**this is my Downloader.java**
package com.example.pgplugins.DownloaderPlugin;
//package com.example.pgplugins.downloaderPlugin;
/*
#author Mauro Rocco http://www.toforge.com
*/
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
import com.phonegap.DroidGap;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader extends Plugin{
#Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
System.out.println("=============i am in head class================");
if (action.equals("downloadFile")) {
try {
return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
}
}
else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
}
private PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
try{
Log.d("DownloaderPlugin", "DIRECTORY CALLED /sdcard/"+dirName+" created");
File dir = new File("/sdcard/"+dirName);
if(!dir.exists()){
Log.d("DownloaderPlugin", "directory /sdcard/"+dirName+" created");
dir.mkdirs();
}
File file = new File("/sdcard/"+dirName+fileName);
if(overwrite.equals("false") && file.exists()){
Log.d("DownloaderPlugin", "File already exist");
return new PluginResult(PluginResult.Status.OK, "exist");
}
URL url = new URL(fileUrl);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setRequestMethod("GET");
ucon.setDoOutput(true);
ucon.connect();
Log.d("DownloaderPlugin", "download begining");
Log.d("DownloaderPlugin", "download url:" + url);
InputStream is = ucon.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
FileOutputStream fos = new FileOutputStream(file);
while ( (len1 = is.read(buffer)) > 0 ) {
fos.write(buffer,0, len1);
}
fos.close();
Log.d("DownloaderPlugin", "Download complete in" + fileName);
} catch (IOException e) {
Log.d("DownloaderPlugin", "Error: " + e);
return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
}
return new PluginResult(PluginResult.Status.OK, fileName);
}
}
**and this is my simple main class:-**
package com.example.pgplugins.DownloaderPlugin;
import com.phonegap.*;
import android.os.Bundle;
public class musicdownloader extends DroidGap {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
}
when i run this program, it is not doing anything. This is my whole project code, so please tell me what is mistake i have done.
Did you follow the instructions from this page where: https://github.com/phonegap/phonegap-plugins/tree/master/Android/Downloader I've used this plugin without issues.
Also, I noticed the URL is an internal IP, does the phone or simulator have access to it?
To install the plugin, move downloader.js to your project's www folder and include a reference to it in your html files.
Create a folder called 'com/phonegap/plugins/downloader' within your project's src/ folder.
And copy the java file into that new folder.
Add the following to res/xml/plugins.xml file
There is a download method from URL in PhoneGap 1.3.0

Categories

Resources