How to dynamically create table in database using greendao or ORMLite? - android

How to dynamically create table in database using greendao or ORMLite? I want to create new table in database when user pressed button, for each new table in database, data model is same but I need table with diffrent name. Is that possible ?

Concerning greendao:
It's not possible to dynamically create a new table. With greendao the code for handling your database is created on your development station by a J2SE-Application (using the daogenerator).
Concerning Ormlite:
I haven't been using Ormlite until now, but I doupt that generating new tables at runtime is possible.
Conclusion:
IMHO a database design, where you have to create new tables at runtime is bad practice, because you won't beable to benefit from ORM-frameworks. A design like that is also very difficult to maintain (if not impossible) and/or to test. On top of that a design like that may be difficult to understand for other developers as it is really uncommon.
Thus you should redesign your database schema.

You can use SQLite
public void createUserTable(DatabaseOperations d, String user) {
final SQLiteDatabase db = getWritableDatabase();
String CREATE_TABLE_NEW_USER = "CREATE TABLE " + user + " (" + UserInfo.NOTES + " TEXT)";
db.execSQL(CREATE_TABLE_NEW_USER);
db.close();
}

Related

Creating new tables automatically vs Giant table

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).

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);

SQLite Database - Create new tables and set Table name through a popup

I am creating an app blocking Application and would like to know a few things:
How to load a list of installed apps into a database table.
Create a new table within the database and set the table name
through an EditText field or an AlertDialog.
Call in selected apps into another activity
List of apps needs to have a CheckBox next to them to select which
apps to carry over to another
Completed Events
I have already managed to populate a ListView with all the installed apps.
I've set up an AlertDialog with everything I need so far, just need
to know how to link that to create a new table and set the entered
text as the table name.
All layouts have been created and set up to accommodate everything,
the problem just lies with the database and calling everything in
I hope I've provided enough details or if this makes any sense at all. Thank you in advance and I hope someone will be able to help me with this problem. If needed I can post segments of my already existing code to make things easier?
For using a Android Database, I recommend to follow this tutorial:
Android | Simple SQLite Database Tutorial
After this tutorial you will understand how the android database works, how you can create tables:
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, "+
"author TEXT )";
// create books table
db.execSQL(CREATE_BOOK_TABLE);
}
And how to
addItemsToDatabase(Object object)
getItemsFromDatabase(int id)
getAllItemsFromDatabase()
updateItemInDatabase(Object object)
deleteItemFromDatabase(Object object)
When you know all this you can create own methods to use!

Android Sqlite how to use one table out of the two created?

I am on Android and this question is of Sqlite :
I have a table (USERLOGIN) which holds the user's credentials (username and password) in it. I have another table ($USER$_PROJS) which holds information of projects for a particular user. Users can create and add projects in there.
[ $USER$ will be a variable which comes from the column username in USERLOGIN table. So its basically a dynamic table creation. ]
Both of these tables are in the same database USER.db.
I have only one LoginDatabseAdapter class and DatabseHelper class which manages both of these.
Now initially when user logs-in, the database is behaving properly. But when inside the user profile when a user tries to create/add project its not inserting the values into $USER$_PROJS table.
I think i need to use the USE TABLE (once the user successfully logs-in his profile) like statement but its giving an error when i try to use it.
I have searched almost all the resources on net but was unable to find the solution !!
Any help would be appreciated !!
CODE RESPONSIBLE FOR CREATING TABLE :
public void createprojtable(String u){
db.execSQL(
"create table if not exists "+u+"_PROJS(ID integer primary key autoincrement,
PROJ_NAME text,DATE text); ");
}
public void insertProjEntry(String u,String projName,
String projdate) {
//db.execSQL("use table "+u+"_PROJS;");
ContentValues newValues = new ContentValues();
newValues.put("PROJ", projName);
newValues.put("DATE", projdate);
db.insert(u+"_PROJS", null, newValues);
}
Have a look at the Cursors for Sqlite in Android. You get Cursors specific to a table. Using the Cursors you can read data from a specific table as such. While updating the data also you can specify table name as one of the parameters. So you can pretty much get what you are looking for using existing APIs.
Have a look at following links :
Android SQLite Database and ContentProvider - Tutorial
android.database.sqlite

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.

Categories

Resources