Tuesday, 28 April 2015

Store Images in Sqlite Database and Search by Date in PHONEGAP


Hi, It is very easy to store images in sqlite in phonegap.
First create a project
Add the plugins:

For Sqlite:
cordova plugin add io.litehelpers.cordova.sqlite
For Multiple images selection from gallery:
cordova plugin add https://github.com/wymsee/cordova-imagePicker.git

For image selection from Camera:
cordova plugin add org.apache.cordova.camera
cordova plugin add org.apache.cordova.media-capture
cordova plugin add org.apache.cordova.media

For Latitude and Longitude:
cordova plugin add https://github.com/Moussawi7/Cordova-GPSLocator.git



First.html:
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.2.min.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.4.2.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>


</head>
<body>
<div data-role="page">
<div data-role="header" class="ui-header ui-bar-a ui-header-fixed slidedown" role="banner" data-theme="b">
<div class="ui-grid-b" style="padding-top: 10px;padding-bottom: 10px;">
<div class="ui-block-a imgback1"></div>
<div class="ui-block-b headertitle"><div>IMAGE SQLITE</div></div>
<div class="ui-block-c logo"><img src=""></div>
</div>
</div>
<div data-role="content" style="margin-top:50px;">
<button onclick="multiimgs();">Multiple images </button>
<button onclick="Cameraimg();">Camera images </button>
<fieldset class="ui-grid-b" id="multi">

</fieldset>
<button onclick="getAllTheData()">View</button>
<div id="map_canvas" style="width:100%;height:100%; position:absolute;"></div>
</div>
</div>
</body>
<script>
document.addEventListener("deviceready", init, false);


Create a variable "app"


var app = {};
app.db = null;


First open the Database and see the condition. The below one is checking whether the app is running in simulator or device
function init() {
app.openDb();
app.createTable();
}Here the database name is "My Database" version is"1.0" space is 200000 app.openDb = function() {
if (window.sqlitePlugin !== undefined) {
app.db = window.sqlitePlugin.openDatabase("My Database");
} else {
// For debugging in simulator fallback to native SQL Lite
app.db = window.openDatabase("My Database", "1.0", "Cordova Demo", 200000);
}
}

Create a table. Here the condition is that whether table with name "MyTable" exists or not. If not table will be created.
app.createTable = function() {
app.db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS MyTable (id INTEGER PRIMARY KEY ASC, text_sample TEXT, date_sample DATETIME, longi REAL, lati REAL)", []);
});
}


app.onSuccess = function(tx, r) {
console.log("Your SQLite query was successful!");
//alert("Saved Successfully");
}

app.onError = function(tx, e) {
console.log("SQLite Error: " + e.message);
}

app.insertRecord = function(t, lat, lng) {
app.db.transaction(function(tx) {
var cDate = new Date();
tx.executeSql("INSERT INTO MyTable(text_sample, date_sample, longi, lati) VALUES (?,?,?,?)",
[t, cDate, lng, lat],
app.onSuccess,
app.onError);
});
}

Getting data from table this function will be called from below function."getAllTheData()". app.selectAllRecords = function(fn) {
app.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM MyTable ORDER BY id DESC", [],
fn,
app.onError);
});
}

var JSONObject = new Array();

function getAllTheData() {
var render = function (tx, rs) {
// rs contains our SQLite recordset, at this point you can do anything with it
// in this case we'll just loop through it and output the results to the console
for (var i = 0; i < rs.rows.length; i++) {
//alert(JSON.stringify(rs.rows.item(i)));
var obj=new Object();
obj.id = rs.rows.item(i).id;
obj.Date = rs.rows.item(i).date_sample;
obj.Lat = rs.rows.item(i).lati;
obj.Lang = rs.rows.item(i).longi;
obj.Img = rs.rows.item(i).text_sample;
JSONObject.push(obj);
}

localStorage.setItem('localdailytasks', JSON.stringify(JSONObject));
window.location.href = "second.html";
}

app.selectAllRecords(render);
}



</script><script type="text/javascript">
var pictureSource; // picture source
var destinationType;
var count = 0;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady()
{
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
var plot = cordova.require("cordova/plugin/plot");
plot.init({});
} Here directly u r selecting multiple images and saving to database
function multiimgs()
{
window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
var multiurl = results[i];


$("#multi").append('<div class="ui-block-b"><div style="width: 70%;padding-left: 35px;margin: 9px;float: right;"><img src='+multiurl+' id="king'+i+'" style="width: 100%;height: 4.6em;border: 2px solid #040000;border-radius:10px;"/></div></div>');
count++;
var lat = 0;
var lng = 0;
window.plugins.GPSLocator.getLocation(function(result){
lat = result[0];
lng = result[1];
},function(e){
lat = 0;
lng = 0;
});
This function will insert image link in to database with that i will be saving lat and long (Optional)
app.insertRecord(multiurl, lat, lng);

}
}, function (error) {
console.log('Error: ' + error);
}, {
maximumImagesCount: 15,
width: 800
}
);

}
function Cameraimg()
{
navigator.camera.getPicture(onCapturePhoto, onFailure,
{
quality: 10,
destinationType: destinationType.FILE_URI
});
}

function onFailure(message) {
alert('Failed because: ' + message);
}

function onCapturePhoto(fileURI) {
$("#multi").append('<div class="ui-block-b"><div style="width: 70%;padding-left: 35px;margin: 9px;float: right;"><img src='+fileURI+' id="king'+count+'" style="width: 100%;height: 4.6em;border: 2px solid #040000;border-radius:10px;"/></div></div>');
count++;
var lat = 0;
var lng = 0;
window.plugins.GPSLocator.getLocation(function(result){
lat = result[0];
lng = result[1];
},function(e){
lat = 0;
lng = 0;
});

This function will insert image link in to database with that i will be saving lat and long (Optional)
app.insertRecord(fileURI, lat, lng);

}





function onError(error) {
alert('code: ' + error.code + '\n' +'message: ' + error.message + '\n');

}
function alertDismissed()
{
}
</script>


</html>

second.html:


<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.2.min.css">
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.4.2.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>

</head>
<body>
<div data-role="page">
<div data-role="header" class="ui-header ui-bar-a ui-header-fixed slidedown" role="banner" data-theme="b">
<div class="ui-grid-b" style="padding-top: 10px;padding-bottom: 10px;">
<div class="ui-block-a imgback1" onclick="back();">BACK</div>
<div class="ui-block-b headertitle"><div>DATABASE</div></div>
<div class="ui-block-c logo"><img src=""></div>
</div>
</div>
<div data-role="content" style="margin-top:50px;">
<input type="date" id="dateid" name="bday">
<button onclick="search()">Search</button>
<fieldset class="ui-grid-b" id="multi">
</fieldset>
</div>

<div data-role="popup" id="image_popup1" data-theme="c" style="width:300px;height:400px;border: 0px;" data-overlay-theme="a" data-dismissible="false">
<button data-role="none" onClick="close_image_popup()" style="border-radius: 10px;background: aliceblue;font-weight: bolder;" class="ui-btn-right">X</button>
<div class="outer-element">
<div class="inner-element">
<img src="" id="album_image" style="max-width:300px;max-height:350px;"/>
</div>
</div>
</div>
</div>

</body>

<script type="text/javascript">
var jsondata = JSON.parse(localStorage.getItem('localdailytasks'));
var count = 0;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady()
{
nosearch();
}

function nosearch()
{
$.each(jsondata, function(index, value)
{
var id = jsondata[index].id;
var today1 = jsondata[index].Date;
var today = new Date(today1);
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!
var yyyy = today.getFullYear();
var post_todaydate = mm+'/'+dd+'/'+yyyy
//alert(post_todaydate);
var Lat = jsondata[index].Lat;
var Lang = jsondata[index].Lang;
var Img = jsondata[index].Img;
$("#multi").append('<div class="ui-block-b"><div style="width: 70%;padding-left: 35px;margin: 9px;float: right;"><img src='+Img+' onclick="bigimgpopup(\'' + Img + '\')" style="width: 100%;height: 4.6em;border: 2px solid #040000;border-radius:10px;"/><span style="" onclick = "removeimg('+id+')" id="countclr">X</span><div>'+post_todaydate+'</div></div></div>');

});
}

This function will display data by searching according to dates u selected and if data is not present in the selected dates it will show "No Results"
Here U can delete an image completely from database by clicking on cross mark and u can display big image by clicking on image.
Please all these features will start from below function


function search()
{
$("#multi").html('');
var compdate = $("#dateid").val();
count = 0;
if(compdate !== "")
{
var kin = new Date(compdate);
var d = kin.getDate();
var m = kin.getMonth()+1;
var y = kin.getFullYear();
var comp = m+'/'+d+'/'+y
$.each(jsondata, function(index, value)
{
var id = jsondata[index].id;
var today1 = jsondata[index].Date;
var today = new Date(today1);
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!
var yyyy = today.getFullYear();
var post_todaydate = mm+'/'+dd+'/'+yyyy
var Lat = jsondata[index].Lat;
var Lang = jsondata[index].Lang;
var Img = jsondata[index].Img;
if(comp == post_todaydate)
{
count = 1;
$("#multi").append('<div class="ui-block-b"><div style="width: 70%;padding-left: 35px;margin: 9px;float: right;"><img src='+Img+' onclick="bigimgpopup(\'' + Img + '\')" style="width: 100%;height: 4.6em;border: 2px solid #040000;border-radius:10px;"/><span style="" onclick = "removeimg('+id+')" id="countclr">X</span><div>'+post_todaydate+'</div></div></div>');
}
else
{
}
});
if(count == 0)
{
$("#multi").append('<div style="width: 70%;padding-left: 35px;margin: 9px;float: right;">No Results</div>');

}
}
else
{
nosearch();

}
}

function back()
{
window.location.href="First.html";
}

function removeimg(idd)
{

if (confirm("Would you like to delete an image?") == true)
{
app.deleteRecord(idd);
}
else
{ }
}

function close_image_popup()
{
$("#image_popup1").popup( "close" );
}
function bigimgpopup(one)
{
//alert(one);
document.getElementById("album_image").src = one;
$('#image_popup1').popup('open');

}

</script>


<script>
var app = {};
app.db = null;
document.addEventListener("deviceready", init, false);

app.openDb = function() {
if (window.sqlitePlugin !== undefined) {
app.db = window.sqlitePlugin.openDatabase("My Database");
} else {
// For debugging in simulator fallback to native SQL Lite
app.db = window.openDatabase("My Database", "1.0", "Cordova Demo", 200000);
}
}


app.deleteRecord = function(id) {
app.db.transaction(function(tx) {
tx.executeSql("DELETE FROM MyTable WHERE id = ?",
[id],
app.onSuccess,
app.onError);
});
}

app.selectAllRecords = function(fn) {
app.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM MyTable ORDER BY id DESC", [],
fn,
app.onError);
});
}



function getAllTheData() {
var JSONObject = new Array();
var render = function (tx, rs) {
// rs contains our SQLite recordset, at this point you can do anything with it
// in this case we'll just loop through it and output the results to the console
for (var i = 0; i < rs.rows.length; i++) {
var obj=new Object();
obj.id = rs.rows.item(i).id;
obj.Date = rs.rows.item(i).date_sample;
obj.Lat = rs.rows.item(i).lati;
obj.Lang = rs.rows.item(i).longi;
obj.Img = rs.rows.item(i).text_sample;
JSONObject.push(obj);
}
localStorage.setItem('localdailytasks', JSON.stringify(JSONObject));
jsondata = JSON.parse(localStorage.getItem('localdailytasks'));
search();
}

app.selectAllRecords(render);
}

app.onSuccess = function(tx, r) {
console.log("Your SQLite query was successful!");
getAllTheData();
}

app.onError = function(tx, e) {
console.log("SQLite Error: " + e.message);
}

function init() {
app.openDb();
}

</script>
</html>



The above code i have done in Android.
Please find and download Apk link

http://107.150.58.162/Apk2Bar/bar/com.syn.newpro_v0.0.1.1.bar










































No comments:

Setting Up Multiple App Targets in Xcode from a Single Codebase

 To create two different apps (like "Light" and "Regular") from the same codebase in Xcode, you can follow these steps b...