How to import sqlite file into my project? - android

I am making an sqlight using eclipse outside the android project
what should I add into my android manifest in order to make it work?
thank you Mathias, lets take this q to another project who generate a SQL file using java
assuming this. How can I set the SQLiteDatabase.NO_LOCALIZED_COLLATORS flag when calling SQLiteDatabase.openDatabase()?
my code over there is
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
/*
*some code
*/
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists "+TABLE_NAME+";");
//stat.executeUpdate("create table "+TABLE_NAME+" (name, occupation);");
stat.executeUpdate("create table "+TABLE_NAME+" ("+VALUE+","+TYPE+","+LETTER+");");
PreparedStatement prep = conn.prepareStatement(
"insert into "+TABLE_NAME+" values (?, ?,?);");
Even when I use:
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
when I use the query :
String s = "Israel";
Cursor cursor = db.query(TABLE_NAME, new String[] {VALUE}
,VALUE + " like " + "'%" + s +"%'", null, null, null, null);
I get an exception .

You don't need to add anything special into the android manifest. You can open the database from anywhere, i.e. also from your sdcard or else. Otherwise, A common place to put the database is in to the assets folder of your application.
When you create the db outside the android project, just make sure you either create the metadata table (as mentioned in the Android docs) or set the SQLiteDatabase.NO_LOCALIZED_COLLATORS flag when calling SQLiteDatabase.openDatabase(). Also you should note that the primary key in all tables is _id. These are the most important things to consider when creating a new DB.
Also helpful regarding the metadata-table might be:
What is the android_metadata table?
No such table android_metadata, what's the problem?
Helpful blog:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

Related

Comparing TEXT variables doesn't work

I'm running into problems when I try to compare TEXT on my Android SQLite DB.
I have a query like that:
select * from myTable where _id='some.text.dots.are.really.there!'
myTable is TEXT PRIMARY KEY. I'm trying to select and update some data in my table. There are there and get returned when I do a SELECT *.
The Android code (with where clause) looks like that:
mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, COLUMN__ID + " = ?",
new String[] {id }, null, null, null);
But
mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, COLUMN__ID + " = '" + id + "'",
null, null, null, null);
works neither. How do I compare TEXT values in SQLite on Android?
SQLite also considers the TEXT CASE (UPER CASE/LOWER CASE) while comparing string, so you can use COLLATE NOCASE, which forces SQLite to ignore TEXT CASE.
Try this:
SELECT *
FROM myTable
WHERE _id='some.text.dots.are.really.there!'
COLLATE NOCASE;
You can use rawQuery for SELECT:
mDb.rawQuery('Query Here',null);
and executeQuery for INSERT/UPDATE/DELET:
mDb.executeQuery('Query Here',null);
I have found the problem: The routines are salting the IDs and therefore they differ from the plain text string.
Stupid error ... Anyways, thank you guys.

How to check if a table exists in Android?

I'm trying to query on a table dormpolicy
String operatorName = "46001";
String selection = "(plmn = '"+operatorName+"')";
URI CONTENT_URI_DORMPOLICY = Uri.parse("content://nwkinfo/nwkinfo/dormpolicy");
cursor = phone.getContext.getContentResolver().query(CONTENT_URI_DORMPOLICY, null, selection, null, null);
I get error log:
SQLiteQuery: exception: no such table: dormpolicy;
query: SELECT * FROM dormpolicy WHERE ((plmn = '46001'))
This issue happen not always in my phone.
It seems that sometimes,when I access the table before the table was created.
Is there any way that before I query the table, I check if the table exist?
And how?
My answer is twofold:
To strictly answer the question, I will redirect you to How does one check if a table exists in an Android SQLite database?
But rather than manually checking for tables' existence, I suggest you use the SQLiteOpenHelper class. This will help you manage your tables in a structured way. That includes handling database upgrades. Have a look at this for a quick start: http://developer.android.com/guide/topics/data/data-storage.html#db

SQL open a table confusion

I needed to store some data related to class periods in an Android project. After looking at my options, I thought a SQL database would be a good choice. Unfortunately, I can't seem to get my statement to actually open a database. My open database statement string goes like this:
"create table "+ DATABASE_PERIOD+" (_id integer primary key autoincrement,"
+KEY_CLASSTITLE+" text not null, "+KEY_PERIOD+" text not null,
"+KEY_XPERIODS+" text not null, "+KEY_DOUBLEPERIODS+" text not null);
I based it off of the Notepad project on the Android website. I just added a few more fields, but it is unable to open the database. If you guys want the error message or some other kind of info, I'll try to get it for you (This is my first time with SQL so I don't really know what is needed to fix this up). Thanks in advance!
The error message I'm getting goes like this:
android.database.sqlite.SQLiteException: no such table: periodData: , while
compiling: SELECT DISTINCT _id, title, period, xPeriods, doublePeriods FROM
periodData WHERE _id = -1
And as it says there, I'm using SQLite.
My code to put some data into the table in my Database Helper class:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CLASSTITLE, title);
initialValues.put(KEY_PERIOD, period);
initialValues.put(KEY_XPERIODS, xPeriods);
initialValues.put(KEY_DOUBLEPERIODS, doublePeriods);
return mDb.insert(DATABASE_PERIOD, null, initialValues);
I started using private static strings to ensure that my calls aren't incorrect (Thanks Barak for the catch!)
Your issue is the table name (as the error message indicates). From the code you show you created a table called "period". Yet you try to query it using the table name "periodData".
Two ways to fix it:
1) Change the table name in your database to periodData (more difficult as it involves re-creating the db).
2) Change the table name in your query from "periodData" to "period".
Check out the dev topic on http://developer.android.com/guide/topics/data/data-storage.html#db
You'll create a DbHelper class to help you open the database and your code will look something like:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
Hope this was helpful.

How to prevent duplicating SQLite database in android?

My app reads an XML file on the internet, takes note of the time and creates/writes an SQLite database. The next time data is required, if the time is >24hrs the database is updated (xml downloaded again).
The problem is that whenever I relaunch the app in AVD it has to re-download and so I notice that all the data in the database is written again (duplicated). So instead of 10 items, I have 20 (10+10 duplicates). If I relaunch again I get another 10 items duplicated.
I thought about how I could prevent the duplication of the database (or delete the old entries), so I decided to increment the database version every time the content is downloaded. I thought this would trigger the onUpgrade() method so the data would be cleared but nothing changes.
Now I am clueless. How should I go about this?
On your database create you'll want to use the UNIQUE constraint. You may not want the ON CONFLICT REPLACE that i use, but you should get the idea.
For Ex:
private static final String DATABASE_CREATE_NEWS= "create table news (_id integer primary key autoincrement, "title text not null, description text not null, date text not null, LastModified text not null, UNIQUE(title, date) ON CONFLICT REPLACE);";
Here is another solid thread that talks about it as well.
SQLite table constraint - unique on multiple columns
Here is some more info on the android sqlite: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
You should create an index on the columns that represent a unique identifier.
see this article on SQLite's website.
CREATE INDEX ix_tblexample ON TableName ( Column1, Column2, Column3 [, Column4, etc..])
Or (as per your comment) you can select the table into a cursor and check for each one.
String sql = "select * from " + tableName + "where column1 = " + param1 + "and column2 = " + param2;
Cursor cur = _db.rawQuery( sql, new String[0] );
if(cur.getCount() == 0)
{
//upload
}

Problems to create new tables when the database already exists

I'm having some strange behaviour.
If the database does not exists, and i execute the following code in my Activity:
listOpenHelper = new ListOpenHelper(ManageListActivity.this);
db = listOpenHelper.getReadableDatabase();
Cursor cursor = db.query(ListOpenHelper.TABLE_NAME, null, null, null, null, null, BaseColumns._ID + " DESC");
The database is create and the table LIST is created, no problem here.
The problem is when i try to execute a similiar block in other Activity:
productListOpenHelper = new ProductListOpenHelper(ProductListActivity.this);
db = productListOpenHelper.getReadableDatabase();
Cursor cursor = db.query(ProductListOpenHelper.TABLE_NAME, null, null, null, null, null, ProductListOpenHelper.NAME + " ASC");
In this case, i get the Exception "android.database.sqlite.SQLiteException: no such table: list: , while compiling: SELECT * FROM list ORDER BY _id DESC"
If i erase the database and execute first the above block, and after the first block, the error will be in the productlist table.
I need to create all my tables in the first execution?
I like to create the tables when the user enter in each of the Activities, there is some good way to do this?
Thanks!
You have two different databases, correct? If not, you probably shouldn't have two different helper classes.
Also, creating helpers as you are may not be ideal. See blog post:
http://www.touchlab.co/blog/single-sqlite-connection/
Please post the code for your helper classes and why you have two different classes.
why you are using two different helpers? i don't think its a good way... You can create the tables in the initially and you can obtain the db whenever you want, with a single helper.

Categories

Resources