Create app database with data in table - android

Simply what I want is when android application is launched for the first time to create database and have standard values in it.
I am successfully initiating CREATE TABLE IF NOT EXISTS and creating a table when application is opened first time. Let's say there will be EUR and USD lines in DB. I want EUR to have already value 100 and USD value 0.
What would be simplest solution for populating database table when table is created/first time application is launched(database table will be created anyway only one time when first time launching app)?
I have read about creating database file in assets folder and then just copying it, creating flag in SharedPreferences to know when application is launched for a first time and then create and populated database or just create method in main onCreate() that check database and fills it if it's empty.

This could be start:
void createdDatabase() {
String databasePath = Environment.getExternalStorageDirectory().getPath() + File.separator + "database.db";
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databasePath, null, null);
String sqlCreateMessages = "CREATE TABLE currencies (\n" +
" id INTEGER PRIMARY KEY,\n" +
" name text NOT NULL,\n" +
" value text NOT NULL\n" +
")";
database.execSQL(sqlCreateMessages);
ContentValues values = new ContentValues();
values.put("name", "EUR");
values.put("value", "100");
database.insert("currencies", null, values);
values = new ContentValues();
values.put("name", "USD");
values.put("value", "0");
database.insert("currencies", null, values);
}

Related

How to delete the rows from a table where a column contains a specific String?

As my title question, I want to delete some rows of table on SQLite where contains specific string.
Here are my methods I tried but there are no any row is deleted. I checked table of SQLite database by get it out and put in to DB Browser for SQLite which is downloaded from https://sqlitebrowser.org/
public void delete1(String table,String COLUMN,String link) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%");
}
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table, "PRODUCTNAME" + "LIKE ?", new String[]{name+"%"}) ;
}
Could you tell me how to do it or how have i to correct code ?
using db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{name+"%"}) ; will only delete rows that start with the value in name.
Perhpas you want :-
db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) ;
Then it would delete rows that contain the value rather than start with the value.
With db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE "+link+"%"); you need to enclose the string in single quotes and assuming that you want to delete a row that contains the value then use :-
db.execSQL("DELETE FROM "+table+" WHERE "+COLUMN+" LIKE '%"+link+"%'");
Using the delete convenience method (the first part) is the better option as it protects against SQL Injection, it properly encloses the value, builds the underlying SQL and also returns the number of affected (deleted) rows.
If you use the following, this will write dome debugging information that may assist in debugging :-
public void delete2(String table,String name){
SQLiteDatabase db = this.getWritableDatabase();
Log.d("DELETEINFO","Attempting to delete rows with \n\t->" + name);
int deletedCount = db.delete(table, "PRODUCTNAME " + "LIKE ?", new String[]{"%"+name+"%"}) >0) ;
Log.d("DELETEINFO","Deleted " + deletedCount + " rows.");
}

Contacts are saved multiple times in Database

Hi guys i have code to add data into Database and that code is called on oncreate. but every time fragment is created its saves data into database again and again. I dont want that. how can i prevent that here is my code to get data and save it to database.
public void getcontacts(){
Cursor phones;
phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()){
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
DataBaseOperations hell = new DataBaseOperations(getActivity());
SQLiteDatabase db = hell.getWritableDatabase();
hell.SaveContacts(name, phoneNumber, db);
}
phones.close();
}
here is code for saving in database.
public void SaveContacts(String Name,String phone,SQLiteDatabase db ){
ContentValues sv = new ContentValues();
sv.put(mDatabase.Tableinfo.Contacts_name, Name);
sv.put(mDatabase.Tableinfo.Contacts_phone, phone);
db.insert(mDatabase.Tableinfo.contacts, null, sv);
}
EDIT- Here is what i have done so far but how do i set a constraint on which it will conflict.I have added an auto increment primary key as unique key but how will they conflict?? but still its saving values again in database.where do i set a primery key as constraint?????
public void SaveContacts(String Name,String phone,SQLiteDatabase db ){
ContentValues sv = new ContentValues();
sv.put(mDatabase.Tableinfo.Contacts_name, Name);
sv.put(mDatabase.Tableinfo.Contacts_phone, phone);
db.insertWithOnConflict(mDatabase.Tableinfo.contacts, null, sv, SQLiteDatabase.CONFLICT_REPLACE);
EDIT- 2 - how would i make unique columns in this kind of query???
private static final String Contacts_Table = "CREATE TABLE "+
mDatabase.Tableinfo.contacts +"("
+mDatabase.Tableinfo.Contacts_name+" TEXT,"
+mDatabase.Tableinfo.Contacts_phone+" TEXT NOT NULL UNIQUE,"
+mDatabase.Tableinfo.isChattris+" TEXT,"
+mDatabase.Tableinfo.status_contact+" TEXT,"
+mDatabase.Tableinfo.Contact_pic+" BLOB"+")";
just Added NOT NULL UNIQUE.
This is the constraint.
Keep the status of the contacts saving in unrelated storage, e.g SharedPreferences. You don't want to rely on any lifecycle triggers, not even Application.onCreate, since that will happen again and again when the app is launched.
Try to update existing entries instead of adding new ones. Decide what the database key should be, and then you can use insertWithOnConflict with the CONFLICT_REPLACE flag to insert if not already in the table or update if it is.
EDIT: to define the constraints so the conflict behavior will trigger, change your CREATE TABLE statement. e.g this will cause duplicate (name,phone) pairs to trigger it. You may want to use some kind of contact ID instead though.
CREATE TABLE mytable (
name TEXT,
phone TEXT,
UNIQUE(name, phone)
)

SQLite connection:application stops working

I am making a diary application in android which is supposed to get some data from text fields.
When I run my app on the emulator, it gets successfully installed but as soon as I give input in the fields and I tap save option in the menu, emulator prompts that diary app has stopped working.
I am not able to find database folder in my app in emulator's file explorer which means my database is not making.
Here is my SQLite connection making and insertion in table code that i am writing in save item.
if(item.getItemId()==R.id.save){
EditText et=(EditText)findViewById(R.id.mood);
String mood=et.getText().toString();
et= (EditText)findViewById(R.id.weather);
String weather=et.getText().toString();
et= (EditText)findViewById(R.id.Text);
String text=et.getText().toString();
Date date= new Date();
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(date);
SQLiteDatabase db= openOrCreateDatabase("DiaryDatabase",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXIST DIARY ('Mood VARCHAR' , 'Weather VARCHAR' , 'Text VARCHAR' , 'Time VARCHAR' , 'Id INTEGER PRIMARY KEY');");
db.execSQL("INSERT INTO DIARY VALUES(mood,weather,text,strDate,NULL);");
db.close();
}
I think your both e.q. DDL and DML statement is incorrect. Try to replace yours with following:
String createQuery = "CREATE TABLE IF NOT EXIST DIARY ("
+ "id integer primary key, "
+ "mood text, "
+ "weather text, "
+ "content text, "
+ "time text" + ")";
Here:
INSERT INTO DIARY VALUES(mood,weather,text,strDate,NULL);
Your origin create statement create PK column as last column and here in your insert statement you are trying to insert NULL as PK that is not allowed and it doesn't make sence since PK is unique identifier of each row.
You should create a SQLite helper class extending from SQLiteOpenHelper to perform all of the database related items such as creating the database and creating the required tables.
Check out this example and use it as a guide:
http://www.vogella.com/articles/AndroidSQLite/article.html

Insert null in Sqlite table

I am trying to figure how to insert a null value into an SQLite table in Android.
This is the table:
"create table my table (_id integer primary key autoincrement, " +
"deviceAddress text not null unique, " +
"lookUpKey text , " +
"deviceName text , " +
"contactName text , " +
"playerName text , " +
"playerPhoto blob " +
");";
I wanted to use a simple Insert command via execSQL but since one of the values is a blob I can't do it (I think).
So, I am using a standard db.Insert command.
How do I make one of the values null?
If I just skip it in the ContentValues object will it automatically put a null value in the column?
You can use ContentValues.putNull(String key) method.
Yes, you can skip the field in ContentValues and db.insert will set it NULL.
Also you can use the other way:
ContentValues cv = new ContentValues();
cv.putNull("column1");
db.insert("table1", null, cv);
this directrly sets "column1" NULL. Also you can use this way in update statement.
I think you can skip it but you can also put null, just make sure that when you first create the Database, you don't declare the column as "NOT NULL".
In your insert query string command, you can insert null for the value you want to be null. This is C# as I don't know how you set up database connections for Android, but the query would be the same, so I've given it for illustrative purposes I'm sure you could equate to your own:
SQLiteConnection conn = new SQLiteConnection(SQLiteConnString());
// where SQLiteConnString() is a function that returns this string with the path of the SQLite DB file:
// String.Format("Data Source={0};Version=3;New=False;Compress=True;", filePath);
try
{
using (SQLiteCommand cmd = conn.CreateCommand()
{
cmd.CommandText = "INSERT INTO MyTable (SomeColumn) VALUES (null)";
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something with ex.ToString() or ex.Message
}

In android, sqlite text field is retrieved using getBlob, not getString

I am attempting to make an android application with a pre-populated database. When learning about how to go about this, I came across this article http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ , which basically takes an existing sqlite database and streams it into the correct location on the android device. The data I had was dealt with in ruby, so I grabbed the sqlite gem, and created a database like so.
db = SQLite3::Database.new( "cards.db" )
db.execute("CREATE TABLE android_metadata (locale TEXT DEFAULT \"en_US\")")
db.execute("INSERT INTO android_metadata VALUES (\"en_US\")")
db.execute("
CREATE TABLE #{##card_table_name} (
_id INTEGER PRIMARY KEY,
name TEXT UNIQUE
)")
cards.each do |card|
begin
db.execute("INSERT INTO #{#card_table_name} (_id, name) VALUES (?, ?)",
card.id, card.name)
rescue => e
puts "#{card.name} (#{card.id})"
puts e
end
end
When I go into the database, both the one made from the ruby script, and the one from using adb and examining the database on the emulator, I get this for the schema.
sqlite> .schema
CREATE TABLE Cards (
_id INTEGER PRIMARY KEY,
name TEXT UNIQUE
);
However, when I pull the data back out in my application, getString can't deal with the name, specifically, this block gets into the exception clause, and prints the name successfully within that block
Cursor cursor = myDataBase.query("Cards", new String[] {"_id", "name"}, null, null, null, null, null, "5");
while (cursor.moveToNext()) {
try {
cards.add(new Card(cursor.getInt(0), new String(cursor.getString(1))));
} catch (Exception e) {
byte[] blob = cursor.getBlob(1);
String translated = new String(blob);
Log.i(MagicApp.TAG, "DB retrival blew up on " + cursor.getInt(0) + ", " + blob + " : " + translated);
e.printStackTrace();
}
}
I can deal with that, but it seems like I shouldn't have to do that. Any one else encountered this, or know what I'm doing wrong?

Categories

Resources