Android ORMLite, use pre-populated database and use it - android

I have a pre-populated database, I hadd .csv and make a database in sqllite manager and imported all values into this database.
Now I put this database into android's assets folder and want to use this via ORMLite in my android application.
Please, need your help and will be thankful to you.

Now I put this database into android's assets folder and want to use this via ORMLite in my android application.
Boy there is a lot of ground to cover here to use ORMLite with this.
The short answer is that you will need to create Java objects which correspond to your database tables. Each Java object should have fields that match the table columns with the appropriate types with #DatabaseField annotations.
For example, if you CSV file was:
# name, id, street
Bill Jones,123,131 Main St.
and your table created is something like:
create table user (name VARCHAR(255), integer id, street VARCHAR(255));
The Java object you will need is something like:
public class User {
#DatabaseField(id = true)
int id;
#DatabaseField
String name;
#DatabaseField
String street;
}
Then you would use ORMLite to read in objects from your database. You should see the ORMLite home page and the Getting Started section of the documentation. For linking up with the existing database, you should read the section of the manual about using with Android.
Any additional questions I'd ask to the ORMLite Users Mailing List.

Related

Migrating auto generate primary key

How can I migrate a primary key field, which was not set to Auto generate before?
From
#PrimaryKey
private int id;
To
#PrimaryKey(autoGenerate=true)
private int id;
Since Sqlite does not support altering columns, my only guess is to migrate the whole table as is and resetting the constraints.
Do I even have to migrate the database during the development process or can I just rebuild it, since my database will change rapidly, so I don't have to migrate every time?
I suggest you to change your approach: add an unique identifier (UID) as alternative way to identify records.
You can define a UID with annotation Entity on your POJO.
#Entity(indices={#Index(value="uid", unique=true)})
publi class Pojo {
..
public String uid;
..
}
When you insert a record in your database, you can define uid field using:
String uuid = UUID.randomUUID().toString();
You can use the UUID field to identify your records, in absolute way. When you migrate to a version to another, you don't work with the old ids, you can always work with UID.

Copy data between tables with some static values

I need to copy data from one table to another. Doing so, I'd like to set manually some static values that will override data from source table. Here is example:
INSERT INTO users (id_usr, name, description, mod_date, user_type) 
SELECT id_usr, name, description, '2014-03-19 15:15:09', 'public'
FROM users_temp
WHERE user_type="" OR user_type IS NULL;
'Datetime' string and 'public' are those static values.
I'd like to know if it is possible, because on Android phone(SQLite from external native library) it doesn't copy any records, but on Windows it works fine.
I've found the problem. My users_temp table was actually a virtual table created from file. While creating that virtual table I have defined wrong charset. It caused that, at the end of every value there was added some kind of white character and condition:
WHERE user_type="" OR user_type IS NULL;
was never fulfilled.
After fixing the problem, statement is executing correctly.

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

What is the best way to implement many-to-many relationships using ORMLite?

I'm currently playing with ORMlite to make a model with tables and relationships.
One relationship is a many-to-many relationship. What's the best way to implement that?
To be more concrete:
Let's say I've got these two tables
Product
id
brand
Purchase
id
A purchase can have several products and one products can be in several purchases.
Using ORMLite I could have a #ForeignCollectionField in each model but I don't think it would work.
The only valid solution I see is to make a third table Product_Purchase to link Product and Purchase with many-to-one relationships.
What do you folks think?
#Romain's self answer is correct but here's some more information for posterity. As he mentions there is an example many-to-many ORMLite project that demonstrates the best way to do this:
http://ormlite.com/docs/example-many
The example uses a join table with the id's of both of the objects to store a relationship. In #Romain's question, the join object would have both the Product and the Purchase object. Something like:
public class ProductPurchase {
#DatabaseField(generatedId = true)
private int id;
#DatabaseField(foreign = true)
private Product product;
#DatabaseField(foreign = true)
private Purchase purchase;
...
}
The id fields get extracted from the objects which creates a table like:
CREATE TABLE `userpost` (`id` INTEGER AUTO_INCREMENT , `user_id` INTEGER ,
`post_id` INTEGER , PRIMARY KEY (`id`) )
You then use inner queries to find the Product objects associated with each Purchase and vice versa. See lookupPostsForUser() method in the example project for the details.
There has been some thought and design work around doing this automatically but right now ORMLite only handles one-to-many relationships internally.
Ok I guess the only way to go is to create a third table Product_Purchase.
It is indicated in a sample project.
You have to create a ProductPurchase class and manage it like it was another object that has to go into your Database.
You can (but you don't have to) have a Collection of Products inside Purchases (and vice-versa) but they will have to be manually updated/created when you load the relations between Products and Purchases from the ProductPurchase linker table. Having those collections mean nothing for the ORM (you won't and shouldn't annotate them).
If anyone is looking for and Android App with the Many-to-Many relationship I worked on an example:
https://github.com/arthurrauter/ormlite-android

Am I understanding how to import my .csv file into sqlite?

I currently have a .csv file with several unlabeled columns of data, which to my knowledge translate to the following datatypes in sqlite:
datetime (in the format 7/19/2011 12:00:00 PM) -> numeric
double -> real
char(1) -> text
float -> real
I can create the database by doing the following:
sqlite> create table myTable (myVar1 numeric, myVar2 real, myVar3 text, myVar4 real);
sqlite> .separator ","
sqlite> .import myFile.csv myTable
Then I copy and paste the newly created myTable.db into the "assets" folder in my project in eclipse. I make a DatabaseHelper class that extends SQLiteOpenHelper, and then I can start using and reading from the database in my Android project.
Am I getting this right? I've never used a database before and I've seen so many vastly different instructions on doing this. Some of my questions are-- do I have to label the columns of my .csv file? Is my .csv file not "simple" enough to just use .import and I'll need to find a program to translate it? I've come across sites saying that I need to rename something (which I don't seem to have) to "_id", and I don't know what this is, where this is, or how to do this, or if it's even necessary, or what it's for. What else am I missing?
I think you are getting it "right" except for that first datetime column. You should use the TEXT type, not a numeric type.
Also, you can inspect your data after the import to see if all is well, especially with that datetime field:
SELECT * FROM myTable ORDER BY RANDOM() LIMIT 10;
UPDATE
In response to the OP's last comment: my understanding of how you store date(time) is that it depends on your context. So if the date in the flat file is in the format "7/19/2011 12:00:00 PM", then without any transformation it'll be imported as TEXT anyway.
Importing csv into database is 15 lines of code task and it gives you more control over this process.
Table columns names like "var3" are just terrible, however there is no need to rename it in database you can just use sql aliases:
select myVar1 _id, myVar2 from myTable
_id is common name for primary key column of table (it's usually numeric column witch must be unique). Every ADK class using datastore assumes relays on it, so it's nice to use this convention.
If you just want read only database you can prepare db locally and find some tutorials how to include it into your app.

Categories

Resources