how to store list into sqlitedatabse? - android

I need to store list of contacts into sqlite database. I've displayed contacts in my project application using Contacts Content Provider. I just need to store the list from emulator into database. Anyone knows how? please help thanks.

Not a big deal.
Transfer your ContactModel into a ContentValue:
ContentValues values = new ContentValues();
values.put("name", name);
values.put("number", number);
then insert it in database :
database.insertOrThrow(databaseTable.getTableName(), null, values)
But keep in mind that it will always be as fast to get a contact from SQLite database as from the ContentProvider since it's pretty the same tech.

Related

How to add a value after being logged in?

I am working in an android studio project and I have a login activity,I created database using SharedPreferences and SQLite;I have created a table which has columns id,email,password,check_in,check_out.
I made it possible to login after I register a user;but I do not know how to insert a data in check_in cell of logged user.
So my problem is that how to make possible to add the time of check_in in table in database after logged in?
And how I can the see the table created using SQLite?
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("check_in", value);
contentValues.put("check_out", value);
// this will insert if record is new, update otherwise
db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
I made it possible to login after I register a user;but I do not know
how to insert a data in check_in cell of logged user.
You would use the SQLiteDatabase's update method something along the lines of :-
ContentValues cv = new ContentValues();
cv.put("check_in",System.currentTimeMillis());
SQLiteDatabase db = this.getWritableDatabase();
db.update("your_table_name",cv,"email=? AND user=?",new String[]{email,user});
And how I can the see the table created using SQLite?
You can
install a product that provides this ability,
copy the database via adb or tools that utilise adb, so that a product that can look at SQLite databases can access the copied file,
extract a cursor from the table and then use this as the source for displaying the data e.g you could use something like
:-
SQLiteDatabae db = this.getWriteableDatabase();
Cursor csr = db.query("your_table_name",null,null,null,null,null,null);
Databaseutils.dumpCursor(csr);
csr.close();

Empty sqlite database when app send on another device

I am developing Android app and I have SQLite database in it. I have inserted records in database. Now when I am sending my app into another device there is empty database!. Please help me
public void createPrincipal(CollegePrincipal principal){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PRINCI_NAME, principal.getName());
values.put(PRINCI_QUALI, principal.getQalification());
values.put(PRINCI_INTRO, principal.getIntro());
// insert row
long princi_id = db.insert(TABLE_PRINCI, null, values);
Log.e("princi id", String.valueOf(princi_id));
}
when ever you create data base it will in the local store of your device , And when you transfer app it wont care you local data you need store those data variables in you code to get in the another device.

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.

How to properly insert values into the SQLite database using ContentProvider's insert() method through a CursorLoader?

I was reading the doc, but I am still not too sure. Its says to use getContentResolver(), but then that really isn't using CursorLoader. So is there a way to do it through CursorLoader? I know how to do it with query(). Are the steps very similar? Even just a link that explains exactly this would be helpful.
Please note, do not link me to the Google doc as they do not have an example that ever uses the insert() method from ContentProvider using a CursorLoader.
Thanks in advance!!
Edit: I should probably mention the reason I am confused with this is because calling a new CursorLoader automatically calls ContentProviders query() method. But how can I do the same for insert?
Check out my blog post on the subject:
Content Resolvers and Content Providers
The CursorLoader has nothing to do with it.
Insertion is a totally different concept... it has absolutely nothing to do with the CursorLoader. When coupled with the LoaderManager, the CursorLoader automatically queries your database and updates itself when the ContentObserver is notified of a datastore change. It has nothing to do with the actual process of inserting data into your database.
How requests to the ContentResolver are resolved
When you insert (or query or update or delete) data into your database via the content provider, you don't communicate with the provider directly. Instead, you use the ContentResolver object to communicate with the provider (note that the ContentResolver is a private instance variable in your application's global Context) . More specifically, the sequence of steps performed is:
You call getContentResolver().insert(Uri, ContentValues);
The ContentResolver object determines the authority of the Uri.
The ContentResolver relays the request to the content provider registered with the authority (this is why you need to specify the authority in the AndroidManifest.xml).
The content provider receives the request and performs the specified operation (in this case insert). How and where the data is inserted depends on how you implemented the insert method (ContentProvider is an abstract class that requires the user to implement insert, query, delete, update, and getType).
Hopefully you were able to wrap your head around that at least a little. The reason why there are so many steps involved is because Android (1) allows applications to have more than one content provider, and (2) needs to ensure that apps can securely share data with other third-party apps. (It wasn't because it wanted to confuse you, I promise).
Inserting data via the ContentProvider
Now that you (hopefully) have a better idea of how the ContentResolver is able to relay these requests to the content provider, inserting the data is fairly straight forward:
First, decide which uri you want to have matched by your content provider. This depends on how you decided to match your uris with the UriMatcher. Each uri you have represents a different means of inserting data into your internal database (i.e. if your app has two tables, you will probably have two uris, one for each table).
Create a new ContentValues object and use it to package the data you wish to send to the content provider. The ContentValues object maps column names to data values. In the below example, the column name is "column_1" and the value being inserted under that column is "value_1":
ContentValues values = new ContentValues();
values.put("column_1", "value_1");
Once received, the content provider will (in your case) pass the values object to your SQLiteDatabase (via the SQLiteDatabase.insert(String table, String nullColumnHack, ContentValues values) method). Unlike the ContentProvider, this method is implemented for you... the SQLiteDatabase knows how to handle the values object and will insert the row into the database, returning the row id of the inserted row, or -1 if the insertion failed.
... and that's how you insert data into your database.
TL;DR
Use getContentResolver().insert(Uri, ContentValues);
Convert Cursor to ContentValues for easy database insertion.
Its says to use getContentResolver(), but then that really isn't using CursorLoader
Besides what Alex said, there's nothing preventing you from iterating through the Cursor returned, putting them into ContentValues and then inserting that (say, to a different DB).
Just an example from the top of my head (a simple Cursor of two String columns):
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor.moveToFirst()) {
ArrayList<ContentValues> values = new ArrayList<ContentValues>();
do {
ContentValues row = new ContentValues();
DatabaseUtils.cursorStringToContentValues(cursor, fieldFirstName, row);
DatabaseUtils.cursorStringToContentValues(cursor, fieldLastName, row);
values.add(row);
} while (cursor.moveToNext());
ContentValues[] cv = new ContentValues[values.size()];
values.toArray(cv);
getContentResolver().bulkInsert(CONTENT_NAMES, cv);
}
}
There are probably more efficient ways to do that (and definitely some integrity checks), but that was my first thought...

Android Update Query

I’m using a database helper to update a table with one row and two fields, I have the following code that that sends two phone numbers through.
dbHelper.updateNumbers(newSmsNumber, newVoiceNumber);
and the following method in the helper.
public void updateNumbers(String newSmsNumber, String newVoiceNumber) {
//Update code here
}
Can anyone show me the code I need to add in the method to update the two fields in the database.
Cheers,
Mike.
ContentValues cv = new ContentValues();
cv.put("SMS", newSmsNumber);
cv.put("Voice", newVoiceNumber);
db.update("[table name]", cv, "ID=?", new String[]{Integer.toString(id)});
There are some gaps to fill up though, the table name, and how you identify the entry you want to update (I put a "ID" field there in that example)
Did not run that code, did not really check, but that should give you an idea.

Categories

Resources