phonegap download file from url to sdcard - android

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

Related

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);

Populated Sqlite DB with Phonegap for 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.

how to upgrade a phonegap plugin from 1.6.x to 2.7?

The code is aim for grap content by using jsoup, and i'm try to upgrade the code
Here is my code so far:
package com.phonegap.g7.plugin;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class UrlFeedJava extends CordovaPlugin {
//#Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
PluginResult r=null;
try
{
String target = data.getString(0);
String selector = data.getString(1);
Document doc = Jsoup.connect(target).get();
Element masthead = doc.select(selector).first();
String content=masthead.toString();
String title = doc.title();
r=new PluginResult(status,content);
}
catch(Exception ee)
{
System.out.print("ee:"+ee.getMessage());
}
return r;
}
}
the PhonegapPlugin.js file
UrlFeed.prototype = {
send: function(success, error, url, selector){
cordova.exec(success, error, "UrlFeedJava", "send", [url, selector]);
}
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('urlfeed', new UrlFeed());
});
the index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script type='text/javascript' src='jquery-1.8.3.min.js'></script>
<script type='text/javascript' src='cordova-2.7.0.js'></script>
<script type='text/javascript' src='PhonegapPlugin.js'></script>
<script type='text/javascript'>
$(function(){
var onSend = function(){
var success = function(data){
$('#show').html(data);
};
var error = function(e){
alert(e);
};
var url = 'http://sports.163.com/12/0618/09/8496QLNG00051C8V.html';
var selector = $('#selector').val();
window.plugins.urlfeed.send(success, error, url, selector);
};
$('#send').bind('click', onSend);
});
</script>
</head>
<body>
<div id='messageDiv'>
<input type='text' id='selector'></input>
<div id='show'></div>
<button type='button' id='send'>Send Me</button>
</div>
</body>
</html>
Especially i don't understand the function of the constructor.
With newer phonegap releases you define the constructor in javascript like this:
var UrlFeed = function(){};
cordova.addConstructor(function() {
if (!window.plugins) {
window.plugins = {};
}
window.plugins.UrlFeed = new UrlFeed();
});
It makes the urlfeed object available to your entire application, you access it anywhere like
window.plugins.UrlFeed.doSomething();
Adding methods to your plugin:
UrlFeed.prototype.doSomething = function(arguments){
//do stuff
//send to phonegap
return PhoneGap.exec(
successCallback,
failureCallback,
'UrlFeed',
null,
[arguments]
);
};
You have to change your java plugin like this:
public class UrlFeedJava extends CordovaPlugin {
//#Override
public boolean execute(String action, JSONArray args,
final CallbackContext callbackContext) throws JSONException {
//your code
return true;
}
}
So basic change is that you do not return a plugin result anymore, but a simple boolean. So remove all plugin result code from your java code.
Please have a look at the simple toast plugin. It shows you how a phonegap plugin is developed https://github.com/giver/cordova-android-toast-plugin
Ref: http://docs.phonegap.com/en/2.8.0/guide_plugin-development_index.md.html#Plugin%20Development%20Guide

How to open contents of a html page which contains Google api for charts in Android emulator

I want to open the contents of a html file which I have saved in my assets folder. The html file contains the chart api provided by the Google graphs.
Content of the HTML file are:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {title: 'My Daily Activities'};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I have written my main activity class as:
package com.example.webapptest;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
setContentView(webview);
InputStream fin;
try {
fin = getAssets().open("web_page_test.html");
byte[] buffer = new byte[fin.available()];
fin.read(buffer);
fin.close();
webview.loadData(new String(buffer), "text/html", "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
But it is showing that web page is down or not available error.

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.

Categories

Resources