I am working on Android Application and i am using Suger ORM for my database operation. Now i have scenario where i have to check if "SomeTable" don't exist then create it and Insert the record and if table already exist and having some record i have to update the records.
I have write this code to check if table don't exist then create the record and save it.
Total_Budget_List = Total_Budget.listAll(Total_Budget.class);
if (Total_Budget_List.size() == 0)
{
for (int i=0;i<Total_Budget_List.size();i++)
{
totalbudget = new Total_Budget(Select_Members.get(i).getId()+"",CurrentDate,per_person_budget+"");
totalbudget.save();
}
}
But i am getting no such table exist in the database.
Now how can i check that if table exist and is there any record in that table.
Surround your code with try / catch block. You can handle SQLiteException if your table not exists.
Related
Im receiving throught BLE data stored in an SD Card. This data is organized in multiple text files, with each file corresponding to a date.
When receiving this data on android i want to save it on a SQlite database.
Thought about using the same logic, creating a table for each day. My question is if its possible to automatically create tables depending on the number of days that is going to be transfered. After some research i found how to add new tables using the onUpgrade method and changing the database version, but this seems only possible by changing the database version manually.
Another option would be by creating a single table for all the data, and add the date as a column.
Any feedback is valuable!
Typically you would use a single table with the date as a column.
It would be possible to dynamically create tables, if they don't exist outside of the onUpgrade method. For each date/file you could, when receiving the file and before loading/inserting the data, either :-
use CREATE TABLE IF NOT EXISTS the_table_with_a_name_that_relates_to_the_date (the_column_definitions)
i.e. if the table exists then the above is effectively a NOOP.
use something like (the below assumes this method is in the DatabaseHelper)
:-
public bolean checkAndAddTable(String tableName) {
boolean rv = false;
SQLiteDatabase = this.getWriteableDatabase();
Cursor csr = db.query("sqlite_master",null,"name=? AND type='table'",new String[]{tableName},null,null,null);
if (csr.getCount() < 1) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + "(......SQL TO CREATE THE COLUMN DEFINITIONS......)");
rv = true;
}
csr.close();
return rv;
}
Note the code is in-principle code ans has not been run or tested and my therefore have some errors.
However, extracting the data from multiple tables would/should need to check if the table exists, to see if data can be extracted which would incur additional processing/complications (e.g. what to do if it doesn't exist).
I have done a few searches and read a number of posts but I am still not successful trying to update a database without losing the data that is already saved.
I created the DB using this tutorial: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
In the new database I want to migrate data from a main table to a new table that will store the user's favourites. Currently, they are stored in the main table. In the onupgrade function I tried renaming the table and inserting the record into the new table. That didn't work. I also tried saving the data to a cursor and then populating the new table but that didn't work. For these methods, I got errors saying that the new/old table cannot be found.
Below is the onUpgrade() function.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE books rename to old_books");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
db.execSQL("INSERT into favourites (_id, type, title, notes,rating) SELECT _id ,type, title, notes, rating FROM old_books where rating > 0;");
db.execSQL("DROP TABLE IF EXISTS old_books;");
}
}
Is there a better way to update the database without losing data using the implementation from the tutorial? All I need to do is copy the favourites from the "books" table and load them to the "favourites" table when users update the app.
onUpgrade is called while the database is open and a transaction is active.
You cannot overwrite the database file at this time (and this would lose all the data in the old file).
Just remove the copyDataBase() call.
if you are using SQLite browser to get preloaded database so you can update the database file then change it's version not create a new database file and keep the data ! Source tutorial .... in my opinion this tutorial is better and more detailed than the one you refereed.
I have an android application which is using Sqlite as database.It has following tables:
Hotels
Locations
Favorites
I am keeping my raw database file in assests folder and when user installs my app i just copies this database to /data/data/package_name/databases directory.Initially Favorites table is empty and it gets populated after user start liking hotels.My problem is that I want to launch my updated version of app with some bug fixes and some new hotels added to the database, so I need to update database of existing users with new hotels and locations without affecting the favorites table.Now if I keep my old approach and update the Database Version Number then application will remove the old database and use the new database but all data in favorites table will be lost.I don't want it to happen.Now problem is how do I update Hotels and Locations table without loosing data in Favorites table.
I know this question was asked long ago, but I had a similar issue and wanted to share my solution, seems to do the trick for me. I'm a novice so feel free to give input-
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//code to keep table data
List<obj> objList = new ArrayList<obj>();
String selectQuery = "SELECT score,list_name,quiz_length FROM obj_table";
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
obj o = new obj();
o.final_score = cursor.getInt(0);
o.quiz_name = cursor.getString(1);
o.quiz_length = cursor.getInt(2);
objList.add(o);
} while (cursor.moveToNext());
}
//done storing data, now upgrade DB from asset file
try {
//my db file is upgraded here
copyDataBase();
} catch (IOException e) {
}
//now insert our saved table data
for (Score obj_rec: objList){
ContentValues values = new ContentValues();
values.put("score", obj_rec.final_score);
values.put("list_name", obj_rec.quiz_name);
values.put("quiz_length", obj_rec.quiz_length);
db.insert("obj_table", null, values);
}
}
Before updating write the contents of you previous table to a file and save it on the sdcard.
Then you may update your database with new version.
And after doing that copy back the data from the backup file(from sdcard) to the updated database. After the successful copying of the backup, delete the file from the sdcard.
Usualy upgrade a database has to be done with SQLiteOpenHelper class. I would advise You to do some tests at Your own device before publish it. You have to increment Your Database Version and call "ALTER TABLE" method from sqlite. This has been discussed in many threads here, the clearest one I think is this one:
Difficulty in upgrading SQlite table
and here is even a article with some solution:
http://joshhendo.blogspot.de/2012/03/android-sqlite-database-upgrade.html
However, a safe way would be to save the old database in a tempfolder, that the user can get back the old one if anything is running into chaos.
For my app, I need to have a database containing one table with 4 columns in it. This tables and its parameters will be static after creation, so that they will stay in the same place with the same data to be listed in a list view.
I have the DatabaseHandler for this purpose, but what I'm asking is how do I define this database in code? Does it build again every launch or is it only with the first launch? How does it work?
There are many ways of doing it. The one i follow is I will create database and tables in launch activity. Then i will insert data by counting the number of records in the table(Only for static table).So if(number of records == 0) then insert data into database. Otherwise do code for your app. It should work.
EDIT
This is the code to get total number of records in the database
In Database Class
YourDatabase
public class YourDatabase extends SQLiteOpenHelper{
//coding for table create and insert records goes here
//Your tables total number of records can be identified by following code
public long yourTableCount()
{
SQLiteDatabase db = getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, YOURTABLE_NAME);
}
}
Your Activity
Calling Database class from your activity
YourDatabase db = new YourDatabase(this);
long numberofrecords = db.yourTableCount();
if(numberofrecords == 0)
{
//Insert your data in to database
//This will happen only in first launch because after that the numberofrecords == total number of records inserted in the database.
}
You can create the database manually using a database manager. Once you have the database defined in your assets folder it will remain there and be compressed within the apk file on build. Try SQLiteManager which has a free trial version that will let you design you database. Or use a firefox addon here: https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
I have created a SQLite database & table in Android.
After performing all the necessary calculations , I have deleted the data from the table of the database by calling the below code.
sampleDB.execSQL("DELETE FROM " + Constants.TABLE_NAME);
Now , I need to write a condition to check that if no data is there for that particular table , I need to show an Alert .
I am unable to find the code to check the condition whether data is there or not for the TABLE , maybe how to check the size of the data within the TABLE.
Kindly provide hints/sample code.
Just query
SELECT COUNT(*) FROM table;