I am attempting to make an android application with a pre-populated database. When learning about how to go about this, I came across this article http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ , which basically takes an existing sqlite database and streams it into the correct location on the android device. The data I had was dealt with in ruby, so I grabbed the sqlite gem, and created a database like so.
db = SQLite3::Database.new( "cards.db" )
db.execute("CREATE TABLE android_metadata (locale TEXT DEFAULT \"en_US\")")
db.execute("INSERT INTO android_metadata VALUES (\"en_US\")")
db.execute("
CREATE TABLE #{##card_table_name} (
_id INTEGER PRIMARY KEY,
name TEXT UNIQUE
)")
cards.each do |card|
begin
db.execute("INSERT INTO #{#card_table_name} (_id, name) VALUES (?, ?)",
card.id, card.name)
rescue => e
puts "#{card.name} (#{card.id})"
puts e
end
end
When I go into the database, both the one made from the ruby script, and the one from using adb and examining the database on the emulator, I get this for the schema.
sqlite> .schema
CREATE TABLE Cards (
_id INTEGER PRIMARY KEY,
name TEXT UNIQUE
);
However, when I pull the data back out in my application, getString can't deal with the name, specifically, this block gets into the exception clause, and prints the name successfully within that block
Cursor cursor = myDataBase.query("Cards", new String[] {"_id", "name"}, null, null, null, null, null, "5");
while (cursor.moveToNext()) {
try {
cards.add(new Card(cursor.getInt(0), new String(cursor.getString(1))));
} catch (Exception e) {
byte[] blob = cursor.getBlob(1);
String translated = new String(blob);
Log.i(MagicApp.TAG, "DB retrival blew up on " + cursor.getInt(0) + ", " + blob + " : " + translated);
e.printStackTrace();
}
}
I can deal with that, but it seems like I shouldn't have to do that. Any one else encountered this, or know what I'm doing wrong?
Related
I am developing an app (that uses SQLite) in Android Studio 2.3 on Mac OS and would like to view the SQLite database, but can't seem to find the sqlite file. Where are the AVM files and specifically the sqlite file?
I found the AVD folder
/Users/<my name>/.android/avd/Pixel_XL_API_26.avd but can't find the user generated data. Any suggestions?
You could always include methods to find out information about the database.
For example you can query the sqlite_master table e.g. :-
Cursor csr = db.query("sqlite_master",null,null,null,null,null,null);
which equates to :-
SELECT * FROM sqlite_master
The are PRAGMA statments that allow you to interrogate/change internals PRAGMA Statements.
Note use rawQuery to obtain information into a cursor but use execSQL to make changes e.g. to set and get user_version (Database Version) respectively:-
db.execSQL("PRAGMA user_version=" + Integer.toString(version));
Cursor csr = db.rawQuery("PRAGMA user_version",null);
You could also look at the data, output to the log, in the tables with something based upon (where tablename would be changed to the appropriate tablename) :-
Cursor csr = db.query("tablename",null,null,null,null,null,null);
String logdata;
while (csr.moveToNext()) {
Log.d("DBINFO","Row " + csr.getPosition());
logdata = "";
for (int i =0; i < csr.getColumnCount(); i++) {
String val;
try {
val = csr.getString(i);
}
catch (Exception e) {
val = "unobtainable";
}
logdata = logdata + "\t\nColumn Name=" +
csr.getColumnName(i) +
" Value=" + val;
}
Log.d("DBINFO",logdata);
}
csr.close();
Note! this only uses getString so will not properly represent some values e.g. double's and floats, if a BLOB then the value will be unobtainable.
In the last time I get some strange reviews on the PlayStore.
Whyever after installing the update of my app, users complain all their app data has been wiped. I have absolutely no idea how this can happen. Database is only recreated if tables do not exist.
Code which is executed after opening database connection:
private void createTablesIfNotExist() {
//query tables
Cursor c = DatabaseManager.executeSelect("SELECT name FROM sqlite_master WHERE type = \"table\"");
//if tables already created, do nothing (+1 because of header table)
if (!((tableAmount + 1) == c.getCount())) {
//meta data table
this.database.execSQL("DROP TABLE IF EXISTS android_metadata;");
this.database.execSQL("CREATE TABLE android_metadata (locale TEXT);");
this.database.execSQL("INSERT INTO android_metadata VALUES('de_DE');");
}
//create event table
c = DatabaseManager.executeSelect("SELECT name FROM sqlite_master WHERE name = \"" + EVENTS + "\"");
c.moveToFirst();
if(c.isAfterLast()) {
this.database.execSQL("CREATE TABLE.....");
}
c = DatabaseManager.executeSelect("SELECT name FROM sqlite_master WHERE name = \"" + ASSIGNED_PRODUCTS + "\"");
c.moveToFirst();
if(c.isAfterLast()) {
this.database.execSQL("CREATE TABLE.......");
}
}
Has anyone an idea? Thanks :)
I think you don't "rewrite" your data from old database to new one.
Android: upgrading DB version and adding new table
Check this link and if it is your problem then if possible you can transfer data for each version to new one and everything will be fine. You have to remember to design database and dataflow to keep in mind that old users can lack some data, so some data in new database can be nullable
I have an app that allows the user to save some chosen rows from a temporary table. The user is able to name the new table.
I am successfully creating a table using the name the user has input, and putting all the chosen rows from the temporary table into the new table.
However, if the table name they enter already exists, I want to notify them via Toast and have them choose another name. I am still learning sqlite - is there a way to do this?
In my head I am using some sort of if statement to check if the table exists, and then executing code, however half of it is in sqlite and half is in java. I'm not sure the correct way to do this. Any suggestions are greatly appreciated!
private void createTable() {
dbHandler.getWritableDatabase().execSQL("CREATE TABLE IF NOT EXISTS " + favoriteName + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT , exercise TEXT , bodypart TEXT , equip TEXT );");
dbHandler.getWritableDatabase().execSQL("INSERT INTO " + favoriteName + " SELECT * FROM randomlypicked");
Try
Cursor cursor = dbHandler.getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName +"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) { //table already exists
//show toast
cursor.close();
return;
}
cursor.close();
}
//create table and insert normally
I am using sqlciper with android to encrypt an existing sqlite db, and ran into a problem that the encrypted db didn't contain my tables, it only contains sqlite_master and android_metadata.
My original db looks like:
shell#umts_spyder:/sdcard $ sqlite3 d000000.dat
sqlite3 d000000.dat
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from sqlite_master;
select * from sqlite_master;
table|android_metadata|android_metadata|2|CREATE TABLE android_metadata (locale TEXT)
table|PageData|PageData|3|CREATE TABLE PageData(File_Path TEXT NOT NULL UNIQUE, File_Content BLOB)
index|sqlite_autoindex_PageData_1|PageData|4|
I paste my encrypting code below, use empty key("") to open the plain db, if using null, NullPointerException raised(For both plain db I mentioned in the end of my post):
File plain = new File(mDbPath); /* /sdcard/d0000000.dat */
File encrypt = new File(plain.getParent(), "encrypted.dat");
encrypt.delete();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(mDbPath, "", null);
String sql = String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s'", encrypt.getPath(), mvKey.getText().toString()); // key is qqqqqqqq
db.execSQL(sql);
db.rawQuery("SELECT sqlcipher_export('encrypted')", null);
db.execSQL("DETACH DATABASE encrypted");
and below is the the code I used to test the encrypted db, there is only "android_metadata, " in the output, my table PageData lost. If I use "select * from PageData" directly, it raises no such table exception:
File file = new File(Environment.getExternalStorageDirectory(), "encrypted.dat");
if(!file.exists())
{
mvBrowse.setText("not exist");
return;
}
String key = mvKey.getText().toString();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, key, null);
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master", null);
String str = new String();
while(cursor.moveToNext())
{
str += cursor.getString(1)+", ";
}
mvBrowse.setText(str); // output is "android_metadata, "
cursor.close();
db.close();
The encrypting should work, because if I open encrypted.dat with empty("") key, it raise "file is encrypted or is not a database" exception, but I can read sqlite_master and android_metadata table with correct key.
I Confirmed the path I tested is the same one I write encryption to;
Tested creating plain db by sqlcipher, using empty key:
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, "", null); /* /sdcard/d000000.dat */
db.execSQL("CREATE TABLE PageData(File_Path TEXT NOT NULL UNIQUE, File_Content BLOB)");
As well as creating it by standard sqlite tools(SQLite Export Professional, and I didn't use BLOB field in this case, just only TEXT and INTEGER);
And tested with two API versions, "SQLCipher for Android v2.2.2" and "SQLCipher for Android v3.0.0".
I also tried to apply the Decrypt precedure as describled in http://sqlcipher.net/sqlcipher-api/ to a encrypted db.
All above got the same result. Will somebody help me? I beleive there is some tiny wrong inside but I can't figure it out.
Finally, I get fixed the problem, by learning from https://github.com/sqlcipher/sqlcipher-android-tests/blob/master/src/main/java/net/zetetic/tests/ImportUnencryptedDatabaseTest.java. (Thanks to #avlacatus, the link has been moved to: https://github.com/sqlcipher/sqlcipher-android-tests/blob/master/app/src/main/java/net/zetetic/tests/ImportUnencryptedDatabaseTest.java). The problem was, when executing the encrypting precedure, one must NOT use execSQL or rawQuery, but use a new introduced method "rawExecSQL. To be clear, the following code just work fine:
String sql = String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s'", encrypt.getPath(), mvKey.getText().toString());
db.rawExecSQL(sql);
db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
db.rawExecSQL("DETACH DATABASE encrypted");
I am trying to figure how to insert a null value into an SQLite table in Android.
This is the table:
"create table my table (_id integer primary key autoincrement, " +
"deviceAddress text not null unique, " +
"lookUpKey text , " +
"deviceName text , " +
"contactName text , " +
"playerName text , " +
"playerPhoto blob " +
");";
I wanted to use a simple Insert command via execSQL but since one of the values is a blob I can't do it (I think).
So, I am using a standard db.Insert command.
How do I make one of the values null?
If I just skip it in the ContentValues object will it automatically put a null value in the column?
You can use ContentValues.putNull(String key) method.
Yes, you can skip the field in ContentValues and db.insert will set it NULL.
Also you can use the other way:
ContentValues cv = new ContentValues();
cv.putNull("column1");
db.insert("table1", null, cv);
this directrly sets "column1" NULL. Also you can use this way in update statement.
I think you can skip it but you can also put null, just make sure that when you first create the Database, you don't declare the column as "NOT NULL".
In your insert query string command, you can insert null for the value you want to be null. This is C# as I don't know how you set up database connections for Android, but the query would be the same, so I've given it for illustrative purposes I'm sure you could equate to your own:
SQLiteConnection conn = new SQLiteConnection(SQLiteConnString());
// where SQLiteConnString() is a function that returns this string with the path of the SQLite DB file:
// String.Format("Data Source={0};Version=3;New=False;Compress=True;", filePath);
try
{
using (SQLiteCommand cmd = conn.CreateCommand()
{
cmd.CommandText = "INSERT INTO MyTable (SomeColumn) VALUES (null)";
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something with ex.ToString() or ex.Message
}