Android create second database after first database is created - android

So I created first database, and now I need to create separate database, zipped it and send it to server.
I'm just wondering if it is doable?
And how can I do it?

Here's the basic logic of what you want to do, it'll have to be supplemented with specific code from here: https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
and here: https://developer.android.com/reference/android/database/Cursor.html
and here: https://developer.android.com/reference/android/content/ContentValues.html
SQLiteDatabase database1 = SQLiteDatabase.openDatabase(<PATH TO DATABASE1>, null, 0);
SQLiteDatabase database2 = SQLiteDatabase.openOrCreateDatabase(<WHEREVER YOU WANT DATABASE2 TO GO>, null);
Cursor cursor = database1.query(<You'll really just have to fill this in with what you're pulling from database1, it's way too specific>);
ContentValues contentValues;
while (cursor.moveToNext()) {
contentValues = new ContentValues();
contentValues.put(<Column key>, <Column value from cursor>)
// I.E. contentValues.put(ID_KEY, cursor.getString(cursor.getColumnIndex(ID_KEY));
// <INSERT THE REST OF YOUR COLUMNS INTO contentValues>
database2.insert(<TABLE_NAME>, null, contentValues);
}
cursor.close();
database1.close();
database2.close();
To send it, that depends on way too many things for me to address. You have the database file now, send it using whatever protocol you please. If you don't know how to do this, search for "Android send File to Server" (try with an without quotes).

Related

Avoid duplicate entries in SQLite

I am writing a small application in android to store basic details about person using SQLite.
I insert data using this function
public void insertData(String user,String p_no,SQLiteDatabase db)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
The above function allows duplicate names to be stored.
So I wrote a function that will first check whether a name exits and then enter.
public void insertData(String user,String p_no,SQLiteDatabase db)
{
Cursor resultSet=db.rawQuery("select NAME from MYTABLE where NAME = '"+user+"'",null);
if(resultSet==null)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
else Toast.makeText(context,user+" already exists",Toast.LENGTH_SHORT).show();
}
But the problem is now toast comes up every time I insert meaning even if the row is unique it is not inserted.
Why resultSet is not null even when there is no such row?
It is because RawQuery never returns null cursor, and that's what your checking criteria is, so it is failing always, and trying to add new value in DB.
I am not able to find the documentation where I learned it, but I will update as soon as possible.
You can check if you have values in cursor using -
if(cursor.moveToFirst())
because it is possible to have an empty cursor. Change your check like
if(cursor.getCount() == 0)
this way, if the cursor is not null, you check if it contains something too.
Probably this is not the best way to handle duplicates, in my opinion. You should mark your column as unique, and use insertWithConflict, to decide what to do in case you have already an entry with that value
Check
if (resultset.getCount() == 0)
Also, create Name as unique key to avoid duplicates. Instead of checking it everytime.

Unable to show updated values from Cursor when live updating SQLite database

I am fairly new to Android and trying to learn how things work module by module. Here's what I am trying to do:
Show a word with a favorite checkbox (image). If a user taps on it then the database is updated and a column in database table stores its value (1 for checked, 0 for unchecked). I am using a cursor to retrieve values of both the word and favorite checkbox. Tapping on the favorite image correctly updates the database without any problem.
The problem I am facing is:
Unless I exit the application and start it again, the cursor doesn't fetch the recent changes made to the database. To explain it further, when I navigate to the next/previous word (using a button at the bottom of screen) the values retrieved aren't the latest ones i.e it seems like the cursor still has the old database values and not the updated ones.
I did search through Google, StackOverflow to get a concrete solution but it seems like I am not using the right search terms. I know this has something to do with updating cursor and the fact that requery is depreciated but again I have lost direction.
[EDIT] Using the below mentioned method to get Cursor:
public Cursor getWords() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"_id", "word", "favourite"};
String sqlTables = "word_list";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
c.moveToFirst();
return c;
}
This method is called when user taps on favorite image to update the database:
public void setFavWord(int markFav, int wordPos) {
SQLiteDatabase db = getWritableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
ContentValues values = new ContentValues();
values.put("favourite", markFav);
db.update("word_list", values, "_id = " + wordPos, null);
}
A cursor is not dynamic; it shows a snapshot of the database at the time the query was executed.
When the database changes, you must execute the query again.
As suggested by #Sreekanth in comments section, I am updating the cursor whenever favorite image is tapped. Although it is working just fine but I think it as a workaround rather than a solution. Maybe I am wrong in saying so.

Android cursor method gives error when i close the database

In Android I query some data from the database into a cursor,after it I close the database. After it when use cursor method it gives error. Anyone can explain why?
This is not really a direct answer, but it is an example of how to do what you are talking about. I have a class called ContactDataSource that allows access and manipulation of my database via a Cursor. To do this, the database needs to be able to be opened and closed. This is handled in my class via the following methods
public void open() throws SQLException{
db = helper.getWritableDatabase();
}
public void close(){
helper.close();
}
I need to be able to get all of my contacts, so that I can utilize their variables, modify them, etc. It would be inefficient, not to mention not very secure, to keep my database connection open the whole time I need the variables in question. I need to store the information from my database somewhere, somehow, on my device. In order to do that I need to call the following method
private String[] allColumns = {ContactDataSQLHelper.COLUMN_ID, ContactDataSQLHelper.COLUMN_CONTACT_NAME,
ContactDataSQLHelper.COLUMN_CONTACT_ADDRESS, ContactDataSQLHelper.COLUMN_CONTACT_NUMBER};
...
public ArrayList<ContactObject> getAllContacts(){
ArrayList<ContactObject> contacts = new ArrayList<ContactObject>();
// Again, without our Cursor, we can't actually point at any of the data we want to
// work with/manipulate
Cursor cursor = db.query(ContactDataSQLHelper.TABLE_CONTACTS, allColumns,
null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
ContactObject contact = cursorToContact(cursor);
contacts.add(contact);
cursor.moveToNext();
}
cursor.close();
return contacts;
}
which will return my list of contacts in the form of ContactObjects. You can see that this method will close our cursor's database connection once it is done. However, before it is closed, it calls cursorToContact(cursor) which will allow us to use our cursor to create a readable ContactObject
private ContactObject cursorToContact(Cursor cursor){
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
String number = cursor.getString(3);
return new ContactObject(name, address, number, id);
}
So in short: Open Connection -> Get what you need from your database -> Store it in an object/variable -> Close connection is the process that needs to be taken.
This can be achieved by call open method -> call getter method -> (if needed) call helper method -> call close method
It is important to note that if you want to reverse the process (save the modified database information) a similar process is followed, just using database setter methods instead of getter methods.
This is expected behavior. Cursors require the database to be open in order to be able to read their data.

Quering SqlLite database where clause Android

Hi I am developing an android app.I am trying to query from the database. I need to fetch everything from the table TASK where dbDate = AlarmDate and dbdTime = AlarmTime.
c = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime= '"+Alarmtime+"'", null);
The problem is ,the cursor c is null.
I am not sure where I am going wrong in the query. Please Help.
Thanks!
Android has binding method to avoid sql inject. You can use the second parameter to provide the variables of SQL.
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = ? AND dbTime = ? ", new String[]{AlarmDate, AlarmDate});
Going by your comment 'I have used db = openOrCreateDatabase("Globus", 0, null); where Globus is the db name', you are not using SQLite properly with android.
What you should be doing is creating class which extends SQLiteOpenHelper, then make sure you override the onCreate and onUpgrade methods, these are the methods where you create tables and make changes, it has been said a hundred times on here so I will provide a link to a tutorial: http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android
When you do database operations, on the class call getWritableDatabase (http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase())
I say call getWritableDatabase because that way you don't need to worry if you can write to it, a writable database is also readable. Just FYI. Ask away for more details.
This should be the process of reading (writing is the same, just use what method you want instead of query):
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();//this should lock the tables you are reading
Cursor c = db.rawQuery("select 1 where 1=?", new String[]{"1"});
if(c.moveToFirst()){
do{
//Do what you want with the row
}while(c.moveToNext());
}
c.close();
db.setTransactionSuccessful();
db.endTransaction();
db.close();
Here is the source code of a database helper I wrote, maybe it will help, read through it, understand how it works. https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/ApplicationDataDbHelper.java?at=master
And if you want to know the reason the open methods exist read through this code
(This class was made from the help of someone elses code)
https://bitbucket.org/FabianCCook/dbhelper/src/af7a8eba8d1a3f139e4170bbef9f1a2d3fdf1b47/src/nz/smartlemon/DatabaseHelper/SDCardSQLiteOpenHelper.java?at=master
SQLiteDatabase db = getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM TASK WHERE dbDate = '"+AlarmDate+"' AND dbTime = '"+AlarmTime+"'",new String [] {});
Make sure you have gotten a readable database for 'db' or it will return null everytime.
Also change the end of your raw query to new String [] {}
Hope this helps, this is what I use in my applications.

Easiest way to enter more than one rows in a table

When the first time i am running the app, i want to create a table and enter some rows into the table. For doing this, i wrote this bit of code and it is working fine:
//Creating the table
db.execSQL(MRM_BOOKING_LOGIN_TABLE_CREATE);
//Setting the values in the table
ContentValues contentValuesLogin = new ContentValues();
contentValuesLogin.put(USER_ID, "asdf");
contentValuesLogin.put(PASSWORD, "1234");
//Inserting a row in the table
db.insert(MRM_BOOKING_LOGIN_TABLE, null, contentValuesLogin);
But i want to enter at least 15 to 20 rows in the table. Is it a good idea that every time after inserting one row, i will clear the ContentValues object (or create another object of ContentValues) and enter another row in the newly created table? In this way, the lines of code will increase a lot as well. I am sure there might be some other better alternative way to do the same. Please suggest
Regards,
I think, the only way to insert multiple records via db.insert is to use a loop. Combine it together with SQLite Transaction and it will speed up the process.
A sample code:
try {
// open the database
db.beginTransaction();
for (your objects) {
ContentValues cv = new ContentValues();
cv.put(COL1, obj.p1);
cv.put(COL2, obj.p2);
//.....
long id = db.insertOrThrow(DATABASE_TABLE, COL_Id, cv);
}
db.setTransactionSuccessful();
} catch (Exception e) {
throw e;
} finally {
db.endTransaction();
// close database
}
You can insert multiple rows using ContentResolver.bulkInsert (Uri url, ContentValues[] values).
More information can be had from here:
Insertion of thousands of contact entries using applyBatch is slow
Hope this will help you.

Categories

Resources