How to search in android sqlite database with speedy way? - android

i tried to search in the sqlite database using the below code :
Cursor cusror;
cursor=db.rawQuery("SELECT * FROM "+ Contactsnew.TABLE02 + " WHERE "
+ Contactsnew.userid + " = " + Contactsnew.userId + " AND " +
Contactsnew.TITLE +
" LIKE '"+search.getText()+"%'");
its working successfully , but in huge database its working slowly. i searched the last days to find third library to work with my own database (Copied from assets to sqlite database) .
i find top five libraries in this article i followed each library but what i find each database is working only with the database that created by itself not with existing database (Already copied from assets).
any help to use any of these library and refer it to my own database or any another library to help me .
Thanks

I suggest creating prepared statements and re-use them. There is an excellent answer on Stack Overflow how to do that. Consider reducing the columns returned by the query, if not all columns are needed. Further, consider creating indexes for relevant columns. test would be the table name and id a column name:
CREATE INDEX idx01 ON test(id);
As a last resort it might be worth trying to remove the LIKE completely and to the regex test while iterating over your cursor.

You have to make sure existing database has the same format of data as new database you adding.
Probably, the simpliest solution here - write some 'migration utility', which will extract existing data and save it to new database.
To speed up queries store different aspects of data into separate tables (not everything in single table), or, if your data has many dependencies, try noSql database (Realm) which not using tables.

Related

Android Sqlite transfer table from one database to another

I've a requirement in my android app.
There is an already existing database A which has a table T. From the next release of the app, I want to create a new database B and MOVE my table from A to B WITH all the existing data.
I am guessing there'd be some way to take dump from the existing db and store that in an asset file. And then use that file to restore the table in new db.
Can't store that data in-memory as it might go to inconsistent state if the app is killed in between.
I am not able to find any well-defined way to do this after spending some time searching in the docs/on the forums.
Please help.
You can achieve this by using ATTACH command of sqlite. First is by specifying the path of the first database.
private static String FIRST_DB_PATH = context.getDatabasePath("Sample.sqlite").toString();
Then you attach it to secondDb
SQLiteDatabase secondDB = secondDBHandler.getWritableDatabase();
secondDB.execSQL("ATTACH DATABASE '" + FIRST_DB_PATH + "' AS tempDb");
Then do the insert query. NOTE: You use secondDB as main
secondDB.execSQL("INSERT INTO main." + SeconDB_table_name + "SELECT * FROM tempDb."+ FirstDB_table_name );
Then finally detach the first db
secondDB.execSQL("DETACH tempDb");
Hope this helps
EDIT:
Do this for dropping table
secondDB.execSQL("DROP TABLE IF EXISTS main." + SeconDB_table_name);
Ok heres how to create a table for secondDB as a copy of the firstDb
secondDB.execSQL("CREATE TABLE main." + SeconDB_table_name + " AS SELECT * FROM tempDb." + FirstDB_table_name);
If what you mean in comment is to drop the first table after moving it to second table, then drop it before dettaching
secondDB.execSQL("DROP TABLE IF EXISTS tempDb." + FirstDB_table_name);

simple sqlite example? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
sqlite example program in android
Hi I'm new to android and I am having some trouble finding a good tutorial for an SQLite database. What I wanted to do was to store a line of data in the database, reference it later and then delete it once its been referenced. As I have said I am new to this sort of thing and have no clue even what any of the syntax is so if there is a simple tutorial out there I would like to know.
try this
try { // creating a database called db and a Table inside it, called
// userdetails. With username and password as columns.
db = openOrCreateDatabase("UserDetails.db",
Context.MODE_PRIVATE, null); // optional CursorFactory
db.execSQL("drop table if exists userdetails");
db.execSQL("create table userdetails " + " ( username TEXT,"
+ "password TEXT);");
} catch (SQLException x) {
x.printStackTrace();
Log.e(LOG_TAG_NAME, "Database creation error");
}
//.........................................................................
// and insert values into the database table.
try {
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('hi','hello');");
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('chris','gayle');");
db.execSQL("INSERT INTO " + "userdetails"
+ " (username,password)" + " VALUES ('v','v');");
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG_NAME, "inserting table values error");
}
String[] columns = { "username", "password" };
Cursor c = db.query("userdetails", columns, null, null, null, null,
null);
now use the cursor to retrieve values
also have a look at
http://developer.android.com/guide/topics/data/data-storage.html#db
hope all this helps
EZ Answer I think.
If I understand your needs I think that you will find a database is overkill. You can do this a lot easier I think with just a few lines of code. If I am correct, a "line of data" sounds like a single String that you want to persist. If that is the case SharedPreferneces is by far your best bet for easy implementation.
Check out THIS link to the Dev-Guide's Shared Preferences Data Storage section
Its as easy as initializing the Preferences, and either putting or asking for a value by key.
On the other hand if you need to store many lines of relational data, search through them, sort them, etc. then a database is what you want.
Generally, I choose the data storage mechanism based on what is being stored and how i want to retrieve it:
Single primitives (and Strings) get stored best in SharedPreferences.
This is a fast and easy implementation. You can get away with storing a couple of values if you need to to represent a more complex class. Sometimes it makes sense to create a helper class that keeps track of complex schemes.
Serializable complex data, like parameterized Collections, that are loaded into memory all at once, long streams of text to be parsed, or if that data is a byte stream it gets stored to a file. This is not as fast and involves catching a lot of potential IO issues. But most objects are serializable or easily made that way.
Tables of data that I want to query or provide a Cursor for because of how long they are go into a database. The start up and resource expenses of a database are huge. Writing all the helper code to use them is a pain in the extreme.
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!
First place to look for tutorials should be the official Android Docs: Link.

Android SQLite, create db with 4 columns and insert values

I am missing something with all of the android SQLite tutorials.
I want to create a SQLite database that holds the autoincrementing key, and four text fields that I will pass in
I intend to pass in this SQL database
private static final String INSERT = "insert into " + TABLE_NAME + "(field1) values (?)" + "(field2) values (?)" + "(field3) values (?)";
but I'm not sure if the android sdk has a proper insert function.
I'm not sure how "Cursor" relates to anything I am trying to do, and I'm not sure how much object oriented initializing I should be trying to as opposed to just calling some built in android sdk functions.
insight appreciated, but please break it down
Will recommend you to go through NotePad exercise here is a link. Specially go through Exercise 1.
And for more depth knowledge you can go through project which I have created. Here is a link
Look for creatFeed function call here. I think will help to answer your problem.

Android SQLite, some SQL basics

I am following this tutorial: http://www.codeproject.com/KB/android/AndroidSQLite.aspx
I must be overthinking this SQLite stuff (in the past my domain server would automatically initialize databases I requested, and I could do queries when desired. never put one together from scratch)
I have some questions about their onCreate function. I never recall using a
CREATE TRIGGER command in my SQL
I only need to create one table with 2 or 3 columns (if you count the primary key)
I should just be able to do
db.execSQL("CREATE TABLE" + tableName +"("+colID+"INTEGER PRIMARY KEY,"+columnName+"TEXT)");
correct?
Do I need a "Trigger" and a "View" ?
If you just need a place to store some data - then Table is enough. But if your logic is more complicated then you'll need additional stuff. Also note that some Triggers are not supported by SQLite: Info from here
You not need to create TRIGGER. Unless it is required. Here is how I implemented in one of my project. Hope this help.
https://github.com/gopalB/FeedReader/blob/master/src/com/feedReader/provider/FeedDB.java
If you do not need a Trigger or a View, then you do not need to create them. It appears that the tutorial is just explaining some of the things you can do.
if SQLite TRIGGER and VIEW are similar to what they're used for in MySQL then no, they are not necessarily for what you're trying to accomplish.
VIEWs are useful when you have complex queries (like when using JOINs to join data from multiple tables).
TRIGGERSs are conditions that are run when you modify a table. (like using UPDATE, or INSERT)
As written, your create statement won't work because of a lack of whitespace. Try:
db.execSQL("CREATE TABLE " + tableName +" (" + colID + " INTEGER PRIMARY KEY, " + columnName + " TEXT)");

Is there an easy way to import data into SQLite?

At the moment I am having to write out each query to insert data into the database separately.
Is there a way I can import a spreadsheet or anything else and end up with this form.?
Is there an auto-increment feature like in normal MySQL?
db.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('3','" +
"Question'," +
"'Answer1'," +
"'Answer2'," +
"'Answer3'," +
"'Answer4'," +
"'Correctanswer'," +
"'Reason');");
Also is there an autoincrement feature like in normal Mysql?
Yes. Take a look at: http://www.sqlite.org/autoinc.html
With regards to your original question; for those cases I better create the database and the initial data in my computer using any of the Sqlite DB Managers out there. Then, I put the database inside the assets directory of the project and instead of creating the database the normal way, I copy the database from there to the handset. This like could be helpful in that case:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
If you can use the SQLite Command Line Shell to prepare your database, you can .import into a table from a file
If your data is (contained in) a spreadsheet, consider using the spreadsheets scripting/macro language to export table(s) INTO a SQLite database
For lots of tables preparing a master database and attach-ing to that from your app may be more efficient and could be done on the handset only
wrt to autoincrement, look at the autoincrement faq too
If I understand, you want to initialize your database with some values, but you don't want to hardcode each query.
In this case you should use JSON to store your data in an external file (like a spreadsheet), then parse this file to get your data and use it to generate your SQL queries.
Here is a tutorial on how to use JSON in android apps.

Categories

Resources