Titanium.DB read Blob from SQLite - android

I'm developing with SDK 1.6.2
I execute a query using the following SQL
var dbrows = db.execute('select item_logo , item_id,item_title,item_content from item');
I successfully get the values for item_id , item_title & item_content. However Ti.API.Info(getFieldByName('item_logo') returns a null value. I have the blob data in SQLLite ITEM table and it is a valid jpeg picture.
Is there any specific processing to be done at Titanium End (Code) to read the Blob data in a loop? Can't find any specific info # Titanium API docs.
Thanks
Vishnoo

you can do this, but the recommended approach is to store the blob as a file and keep the native file path in the database.
See this response from Appcelerator
http://developer.appcelerator.com/question/97041/imageview-sqlite-blob-example-not-working

Related

sql lite dynamic Query for sqllite-pcl xamarin forms

i have created dynamic tables in Xamarin forms by using SQLite queries
string cmdStr="CREATE TABLE Mytable ....";
i am able to create table using
SQLiteCommand command = new SQLiteCommand(sqlitConnection);
command.CommandText = cmdStr;
command.ExecuteNonQuery();
the above code is working fine ,i am able to save data to sql lite db
i am unable to get data from db using command.ExecuteQuery() using command string as "select * from Mytable". as seen in screenshot i am unable to fetch content from dynamic tables,please suggest any alternatives
enter image description here
The error message tells you exactly what is wrong - you are not specifying a Type argument T. The correct syntax is
List<T> results = command.ExecuteQuery<T>();
where T is the name of the class you are mapping the results to

How to implement SQLITE_LIMIT_LENGTH?

I am using SQLite in my RN apps with help of react-native-sqlite-storage. Then, one of my table has a column which contain a very long string. When I try to insert the string, no error occured. But, when I select the row, it return null. This open issue is similar with my problem.
Then, I found this documentation. It said that
During part of SQLite's INSERT and SELECT processing, the complete
content of each row in the database is encoded as a single BLOB. So
the SQLITE_MAX_LENGTH parameter also determines the maximum number of
bytes in a row.
The maximum string or BLOB length can be lowered at run-time using the
sqlite3_limit(db,SQLITE_LIMIT_LENGTH,size) interface.
My question is, if I have this piece of working code to select data from a table:
const db = await SQLite.openDatabase('databasename', 'default');
db.executeSql('SELECT * FROM tablename', [], (res) => {
console.log(res.rows.item(0));
}, err => console.log(err));
How to implement sqlite3_limit(db, SQLITE_LIMIT_LENGTH, size) to above code in order to increase the SQLITE_LIMIT_LENGTH?
You can't easily. Android's default sqlite implementation doesn't provide access to it. You would need to import your own version of the sqlite Java library (which is really a C library accessed via JNI), then provide your own RN module to access it in Java, then use only that module to access the db at all. Its a lot of work. How large is this string? You may want to consider storing it in a file and putting the filename in the db.
The issue you linked particularly mentioned images. Sqlite is not really a good solution for storing images, for a variety of reasons. Use a file and store the filename for that.

PDF files on SQLite database

Can I add books to my SQLite database in android??
If yes, how?
I want to put the books on database because I've too many books to add to the android app and I don't want to make the size of the Application too much.
There's a limit of 1MB on internal assets due to dynamic decompression; the 1MB >limit also seems to apply to Cursor blobs but this doesn't seem to be >documented anywhere.
Generally you should avoid blobs in SQLite as they perform poorly; instead, >save the blob data as a file and store the location of the file in your DB
I won't recommend storing pdf flies in SQLite, you can just provide a simple link to download it to the user. but if you want to store it here you can do something like this.
First, you need to convert the pdf file into a byte array
import java.nio.file.*;
Path pdfFilePath = Paths.get("/file/path/your_file.pdf");
// Read file to byte array
byte[] pdfByteArray = Files.readAllBytes(pdfFilePath );
// Write byte array to file
Files.write(pdfFilePath , pdfByteArray);
You're looking for BLOB to store the data in android SQLite.
BLOB - The value is a blob of data, stored exactly as it was input.
Here's an example of making a table with two columns - an id and some data, which is a BLOB:
just for an example, you can create a table like this
CREATE TABLE t1 (id INTEGER PRIMARY KEY, data BLOB);
You can't do it. you cant store files in SQLite database. You will store your files in asserts folder.

MySQL to Sqlite sync from PHP to mobile app (iOS/Android)

To sync a mysql database with sqlite database using a PHP web app, I am going to
create a "view" mirror of SQLITE tables in MySQL
select changed data on mirror "view" in MySQL
use mysqldump to dump the sql for sqlite and save it in a file on server
download that file from mobile
import data directly to sqlite
another approach would be not using a middle "view" table and dump data using "SELECT" or mysqldump and parse it on the device or server, so it would be readable by sqlite
is there any disadvantages in creating a mirror "view" for each table that SQLITE needs on client devices? or is there another 'standard 'way to sync these 2 which i did not find on the internet?
Edit: after searching and coding some more finally i decided to go like this:
build "insert into ..." statement for sqlite from PHP on the server and save it to a zipped file
download the file on mobile and insert extracted sql directly to SQLITE
here is the php code for generating mysqldump like output:
/** key [SQLITE column name] => value [MySQL select column] */
$table_structure = array(
'id' => 'id',
'title' => 'title',
'type' => 'COALESCE(type, "")', /** u need to wrap any column that is nullable like this **/
'flags' => 'COALESCE(type, "")', /** u need to wrap any column that is nullable like this **/
'view_field' => 'view_field',
'view_year' => 'view_year',
....
....
'updated_at' => 'UNIX_TIMESTAMP(updated_at)');
$into_query = '';
$into_values = '';
$indexer = 0;
foreach ($table_structure as $sqlite => $mysql) {
$into_query .= (($indexer !== 0)? ',':'').$sqlite;
$into_values .= (($indexer !== 0)? ',",",':'').'"\'",'.$mysql.',"\'"';
$indexer++;
}
$output_filepath = "some where nice";
$query = 'SELECT CONCAT("INSERT INTO '.$table.'('.$into_query.') VALUES(",'.$into_values.',");") FROM '.$table.' ' ... "INTO OUTFILE $output_filepath CHARACTER SET utf8";
I hope it's a good approach and may help someone some day :)
Approach 1: using sqlite db file
whatever step you have mentioned in question is correct. this approach used when you have to send lots of data(many tables) from device to web/php vice versa.
its takes time in slower internet connection as well in 2G. in 3G its fast(its also depends on whatever code you have written at mobile/PHP to upload & download file).
make sure database file size is small if it large then make zip file which include database file.
Approach 2: make using json (SELECT *) parse in device
this one is very long process when you have lost of table which have lots of fields. you have to get data from table one by one, send it to server/php its send back data after process. then you have to again insert data in device table.
this is also depends on INTERNET as well you code. its too slow for devices and take more time.
common things in both approach send/receive data only when its needed or on those which require for devices/PHP. do not send unused data to work fast.

what is the exact process of using the Database in phonegap android?

I am new to Phonegap. I am trying to implement an application in Phonegap Android. For the past two days,I am scouting for a proper way of accessing the database and retrieving it from the same.I did not find an answer to my questions
I have learnt that Phonegap does not support SQLLITE but supports the W3C Web SQL Database Specification and W3C Web Storage.
At the same time I noticed few plugins for Phonegap 1.5..which does not exist now. At the same time i found that W3c database provides a limited storage of 5MB for iOS.
I found this SQL Plugin for Phonegap Android PhoneGap-SQLitePlugin-Android Is it advicable to use this or any other method. Please,guide me.
So,if you have any sort of example of accessing the database that can be followed please share it.
I made an app recently that required this, targetting the Android and iOS. You can use a combination of the following ::
1. LocalStorage ::
Check for localStorage
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
Set an item into LocalStorage
localStorage.setItem("bar", foo);
or
localStorage["bar"] = foo;
Get an item from LocalStorage
var foo = localStorage.getItem("bar");
or
var foo = localStorage["bar"];
2. SQLite Database (more convenient, more persistive)
Set up your DB
var shortName = 'BHCAppDB';
var version = '1.0';
var displayName = 'BHCAppDB';
var maxSize = 65535;
if (!window.openDatabase){
alert('!! Databases are not supported in this Device !! \n\n We are sorry for the inconvenience and are currently working on a version that will work on your phone');
}
db = openDatabase(shortName, version, displayName,maxSize);
createAllTables(db);
Create your Tables
function createAllTables(db){
db.transaction(function(transaction){
transaction.executeSql("CREATE TABLE IF NOT EXISTS Profile(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, gender TEXT,age INTEGER)");
}
Execute an SQL Query
transaction(function(transaction){
var rowCount = 'SELECT * FROM Profile';
transaction.executeSql(rowCount,[],function(transaction,result){
if(result.rows.length == 0){
var sqlString = 'INSERT INTO Profile (name,gender,age) VALUES("自己","Female",18)';
transaction.executeSql(sqlString);
}
});
});
3. Native Storage on all devices
This is the best part of Phonegap. You can call a native plugin class on all the devices using the Phonegap plugin call. During the call, you can pass parameters to the class, and the native class can store your data in the OS itself.
For example :: in iOS, you create a plugin .h & .m class and register it with the Cordova.plist file. Once that's done, you need to send a call to the class from JavaScript using Phonegap. Once the parameters have been received using NSDictionary or any other NSArray type, you can call a CoreData class to store UNLIMITED amounts of data. You'll never run out of memory .
This can be done in a similar fashion for all the rest of the OS's also :)
For Encryption try the following :: SQLCipher
Here is some additional information on working with an existing SQLite database. In this example encrypted.db is that brand new database you create and pragma.
ATTACH DATABASE 'encrypted.db' AS encrypted KEY 'secret'; -- create a new encrypted database
CREATE TABLE encrypted.t1(a,b); -- recreate the schema in the new database (you can inspect all objects using SELECT * FROM sqlite_master)
INSERT INTO encrypted.t1 SELECT * FROM t1; -- copy data from the existing tables to the new tables in the encrypted database
DETACH DATABASE encrypted;

Categories

Resources