Estentiate SQL database with CSV file in Android App - android

I have a file with 100 records containing Name,phone,email.
The application should read this file and put it into SQL database in android app. Then I need to display names in a scrollable view with option to display full data on certain record.
I can't figure out the way to read this data from a file and add populating a database with it.
I assume that I need to read file records one by one until the end of the file and then insert into a Database using SQL statement. But How I read this using delimiters and where do I put this insert method? I assume it can be onCreate in a DataBaseHelper class?

You will have to read the file line by line and split the string by comma. Once you have the 3 strings (Name, phone and email), you can do the following:
// assuming you are using BufferedReader
String line = null;
while((line = br.readLine()) != null) {
String[] parts = line.split(",");
ContentValues values = new ContentValues();
values.put("Name", parts[0]); // Assuming they are in the order you mentioned
values.put("phone", parts[1]);
values.put("email", parts[2]);
// Insert the data into the database
db.insert(TABLE_NAME, null, values); // insert your table name
}
The above code snippet will iterate through the file, read it line by line, decompose each line and store the data in the database.
To answer the second part of your question - yes, you may have this inside the onCreate method of your database helper. But you can also have it elsewhere.
Don't forget to close any database connection that you may have.

Related

Where to store values to be inserted to SQLite at installation

I am new for SQLite and here is the story;
I'm developing an apk which is a kind of quiz application. I want to store the questions and answers in SQLite database. ( I am also not sure if this is the best way to store data, in SQLite )
In onCreate() method I should create the db and insert all questions, answers etc. So, I'm not sure where to put the data that will be inserted to db before insert them to db tables.
I mean;
values.put("key", "What is abc");
** insert
values.put("key", "What is def");
** insert
values.put("key", "What is ghi");
** insert
values.put("key", "What is xyz");
** insert
...
where should I get those strings (What is bla bla) to insert to table ?
If this was a windows application, I would put them in a .txt file, read from there, and insert rows.
In android, I don't know.
Thanks for any suggestions.
I am also not sure if this is the best way to store data, in SQLite
There are worse choices. :-)
In onCreate() method i should create the db and insert all questions, answers etc.
I'd prepare the database ahead of time, package it with your app, and deploy it using SQLiteAssetHelper. This would be easier to write, easier to maintain, and faster to run.
You can use this to read a text file.
Once you have that in your SQLiteOpenHelper#onCreate() method you would add your default values.
One way to do this would be:
Store the data as XML file in your res/raw folder.
Create a Parser. (DOM would work for a small file. SAX would be better if the file size is large)
Parse the data in onCreate and insert the values.
For example:
` public void onCreate(SQLiteDatabase db) {
ArrayList quizDataList;
quizDataList = ParseQuizData.getQuizData(context);
ContentValues values = new ContentValues();
try {
// Create Database
db.execSQL(TABLE_CREATE);
for (Iterator<QuizData> iterator = quizDataList.iterator(); iterator.hasNext();) {
QuizData quizData = iterator.next();
values.put(COLUMN1, quizData.getAttributeFirst());
values.put(COLUMN2, quizData.getAttributeSecond());
db.insertOrThrow(TABLE_NAME, null, values);
}
} catch (Exception e) {
e.printStackTrace();
}
`

Build SQLite database from JSON file in runtime - is it Good?

I need opinion regarding rendering of data in android app. I have all the data stored in a json file abc.json which is in res > raw folder. i have a class that then reads data from that json file and build SQLite database when the app runs and later on i'm performing all operations like searching the data using sql queries for that database. But i am afraid if thats not a good option and the code is not optimized because code now contains so many functions for adding the items to database.
For example, json file has Authors, books, keywords, references, acknowledgements, subauthors and when the database is built, data is read and a specific function is called for each item. I'm just concerned because of too many functions as one for each item. Like whenever json is parsed for an item, e.g author, it calls addAuthors function to add that to database. Following are 2 of the functions for example.
//Sample function code for adding authors to db
public void addAuthors(Integer id, String Name, String is_corresponding) {
ContentValues value = new ContentValues();
value.put("_id", id);
value.put("NAME", Name);
value.put("IS__CORRESPONDING", is_corresponding);
authors_id = database.insert(TABLENAME_AUTHOR, null, value);
}
//example function for adding keywords to db
public void addKeyWord(String KeyWords, Integer id) {
ContentValues values = new ContentValues();
values.put("KEYWORDS", KeyWords);
values.put("_id ", id);
database.insert(TABLENAME_ABSTRACT_KEY_WORDS, null, values);
}
I need help with optimizing my code. Is there any way to optimize the current code ? Kindly help me with this and suggest some improvements for it. Thanks in advance
I would recommend bundling a sqlite database as an asset in your APK instead of bundling the JSON file and then inserting the data into a database. If your data isn't changing, you can then get rid of all your insert functions. You will also save the cost of creating and populating your database dynamically.
You can use the methods described here to create your database and to copy it from the assets of your APK. Be sure to copy it first before you try to open in in your app -- you can't open it directly as an asset.

Insert into SQLite

I am trying to insert text messages from an inbox to a SQLite Database, but due to some special characters/symbols it doesn't insert properly.
I went through some question in Stackoverflow but nothing seems useful.
I got this code, but it is not working.
data.execSQL("INSERT INTO recor(text) VALUES('"+DatabaseUtils.sqlEscapeString(messag)+"')");
My database has only one field in it and am trying to insert details of messages along with it. I am putting the details (type, time, number, message) to a single string message and recor is my table name.
This is what I get as toast when I use a try catch loop.
Error is near:
"FROM":syntax error:INSERT INTO recor(text) VALUES("FROM 15555215556 Message:-MSG")
Uses the DatabaseAdapter's insert method instead. e.g.
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, value);
dbAdapter.insert(TABLE_NAME, null, values);
it looks like your column name is 'text'? this must be wrong, as text is a keyword in sqlite.
Your final SQL string seems to include two sets of quotes around the string you are inserting, so I assume the DatabaseUtils.sqlEscapeString method adds its own quotes around the string.
Therefore, your code should be:
data.execSQL("INSERT INTO recor(text) VALUES("+DatabaseUtils.sqlEscapeString(messag)+")");

Populate an SQLiteDatabase in Android with static data

I have a database with multiple tables. One of these tables (sport) is where i have to put a static list of object, each one with an _id, name, logo and an int. The _id will be used by other tables to do some queries (eg. select from "table X" where sport_id = _id), so it shouldn't change overtime (is there a way to update all the reference to this _id if it will change?).
Where should i put the code (i think it will be a simple list of db.insertSport()) to make it add this row only one time (and check if the row number grow, to add the new ones)?
There won't be much row, 50 at the best.
I think I would make a method in the dbHelper to insert that data, then call that method immediately upon app start. I'm making a couple of assumptions here... first that you are shipping this static info with the app and when you want to add more info you will be shipping a new version.
You could store the data as a text file in your assets folder and then read the file in execute a batch insert in the method.
If you set it up right (use insertWithOnConflict and the CONFLICT_IGNORE flag in the method) it will only add the new rows (if any) each time so you can run it every time the app starts and not worry about duplicate data or crashes for constraint violations.
If you only want it to run the once and then again when there is additional info, put a version number in the text file and check that against the previous one (which you can store in SharedPreferences).
EDIT
Example of using insertWithOnConflict:
public long createItem(String yourdata) {
ContentValues initialValues = new ContentValues();
initialValues.put(YOUR_COLUMN, yourdata);
return mDb.insertWithOnConflict(YOUR_TABLE, null, initialValues,
SQLiteDatabase.CONFLICT_IGNORE);
}
You can read up on the SQLiteDatabase class (which has the constants and methods) here

Dynamic Database Backup for certain tables

I need to backup just some of the tables in my main database. The other tables are reference and are static so do not need to be backed up.
I have created a new blank DB that is on the SDCARD. Can I access the DB directly on the SDCARD or do I need to copy it when its finished backup?
The real question is can I iterate through the fields in each record in a loop or something so I dont have to have hundreds of line of code, one for each field.
In VB .NET I would do something like
For X = 0 to RS.Fields.Count
NewRS.Fields(x).value = Rs.Fields(x).value
etc... How wound I do that in android?
I wrote a class to handle this. Yes my DB is at least 95% reference...
Here is the guts of the code:
Cursor c = DbBak.rawQuery(Sql, null);
String Cn[] = c.getColumnNames();
if (c != null ) {
if (c.moveToFirst()) {
do {
for ( x=0; x< c.getColumnCount(); x++)
{
newRow.put(Cn[x].toString(), c.getString(x));
}
Db.insert(TableName, null, newRow);
}while (c.moveToNext());
Unless your reference tables make up 95% of your database size, I'd just copy the database file using standard Java file I/O, while the database is closed. That will be substantially faster than trying to schlep the data over cell-at-a-time.

Categories

Resources