Create Android SQL Database with a few pre populate data - android

I've gone through many examples here, but all seem complicated and most of them are for large data. I'm new to both Android and also SQL. What I want to do is just pre-populate my SQL database with some data.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT, feed TEXT, lat REAL, lon REAL);");
ContentValues cv=new ContentValues();
cv.put("name", "Hi");
cv.put("address", "There");
cv.put("type", "delivery");
cv.put("notes", "");
cv.put("feed", "");
cv.put("lat", "");
cv.put("lon", "");
getWritableDatabase().insert("restaurants", "name", cv);
}
There is no error but unfortunately no data is inserted as well. This should be very simple, please help me?

Use db.insert("restaurants", "name", cv);

Your approach is fine, inside SQLiteOpenHelper#onCreate() is the right place to put initial data since that is where you create the database in the state you like it to be.
But inside onCreate you use db.insert("restaurants", "name", cv) directly. You are not finished to create the writable database you try to get via getWritableDatabase() at that point. Not sure if that is the problem but it could be.

Related

Dynamic table creation on button click in SQLite

I am creating a login application and I wanted to create a table for each user when they click the register button. The problem is, I am using their unique email id as table name. Later I learned that table names cannot have special characters like "#". Please suggest me a way to create table with names having special characters like "#". Or else, please suggest me a way to create tables with unique names for each user when they click the register button.
Please Note :"TABLE_NAME" in the code given below is another table containing registered user details.
The code is given below:
public boolean insertData(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("create table "+email+"(Choice TEXT, Q1 INTEGER, Q2 INTEGER, Q3 INTEGER, Q4 INTEGER, Q5 INTEGER)");
ContentValues cv = new ContentValues();
cv.put(NAME, name);
cv.put(EMAIL, email);
cv.put(MOBILE, mobile);
cv.put(PASSWORD, pass);
long result = db.insert(TABLE_NAME,null,cv);
db.close();
if(result == -1)
return false;
else
return true;
}
In SQL, identifiers can be quoted with double quotes. Any double quotes inside the identifier must be doubled to escape them; and in Java strings, double quotes must be escaped with a backslash:
String sqlTableName = "\"" + email.replace("\"", "\"\"") + "\"";
db.execSql("CREATE TABLE " + sqlTableName + "...");
However, putting data into the table name is a bad idea, because it cannot be queried and modified like all your other data.
Better use a single table, and put that information into another column:
CREATE TABLE Users(EMail TEXT, Choice TEXT, Q...);

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)
)

How to skip the primary key when inserting ContentValues in SQLiteDatabase

I have a little Problem with an insert-Statement in my Android-App.
Here is the code:
public void addNote(Note noteItem, int modulNummer){
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NOTE, noteItem.getNote());
cv.put(COLUMN_NOTEBESCHREIBUNG, noteItem.getBeschreibung());
cv.put(COLUMN_MODULID_FK, modulNummer);
db.insert(NOTETABLE, null, cv);
}
Now my problem. The first column in my table is an auto increment pk. And so i want to skip the first column and i want to begin the insert in the second column. How can i skip this first column?
Update
I've already deleted the .put for the first column. "COLUMN_NOTE" is my second column.
My table-structure looks like this:
id INTEGER AUTO INCREMENT
note double
beschreibung TEXT
modul_id INTEGER
UPDATE 2
I don't know why, but now it works. Thx for your help guys.
If you have a table like the following one:
private final String TAB_GROUP_ADD = "CREATE TABLE groups (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL);";
And you use the following insert command:
ContentValues values = new ContentValues();
values.put(K_TITLE, title);
values.put(K_DESCRIPTION, description);
db.insert(TAB_GROUP, null, values);
Everything should go fine. The primary key field "id" will no be filled in by Java and the SQLite Database will do it for you.

Android SQL Blob

I'm trying to store and array of bytes (byte[]) into a DB. I have the array of bytes, a content provider and a database. When I try to insert into the Blob the insert returns -1. Can somebody show me how to get this done.
Insert
byte[] inData = nw.receive();
ContentValues values = new ContentValues();
values.put(InDatabase.Columns.DATA, inData);
values.put(InDatabase.Columns.SIZE, inData.length);
NetService.this.getContentResolver().insert(InContentProvider.CONTENT_URI, values);
Content Provider
mDB = mDBHelper.getWritableDatabase();
Long rowId = mDB.insert(mDBHelper.tableName(), null, aValues);
Database
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE table " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, data BLOB, size INTEGER);");
}
Like I said If I don't put the values.put(InDatabase.Columns.DATA, inData), it works perfect.
So the implementation was right, the problem was with the SQLiteDatabaseHelper. I did not implement the onUpdate() method. Because my database already existed on the device with a different layout (the BLOB field did not exist) the insert method failed.
A quick uninstall of the .apk fixed the problem. I could also implement the onUpdate method so when the database version changes there is a table drop or update.

SQLiteConstraintException with Android

I'm creating a dataBase to insert a *unique patient *(no more than one), so I just created a database that doesn't autoincrement its id like this:
CREATE TABLE IF NOT EXISTS PACIENTE(idPaciente INTEGER PRIMARY KEY, nombre VARCHAR(100) NOT NULL, apellidos VARCHAR(100), email VARCHAR(100), genero CHAR, edad INTEGER NOT NULL, peso INTEGER, kMedico INTEGER, pkHistorial INTEGER, pkConfProg INTEGER, altura INTEGER, FOREIGN KEY (pkMedico) REFERENCES MEDICO(idMedico), FOREIGN KEY (pkHistorial) REFERENCES HISTORIAL(idHistorial), FOREIGn KEY (pkConfProg) REFERENCES CONFPROGRAMA(idConf));
As you can see, the way to add a patient here is tell the database the idPaciente explicitly.
So I used this code to insert a patient:
public long addPaciente(BDPaciente pac)
{
ContentValues cv = new ContentValues();
cv.put("idPaciente", 1);
cv.put("nombre", pac.getNombre());
cv.put("edad", 26);
try
{
db.insert("PACIENTE", null, cv);
return -1;
}
catch (SQLiteConstraintException e)
{
return -100;
}
}
As you can see, what I'm trying to do is insert a patient, and then, if it is inserted before, catch the Exception and throw it to my parent Window. The thing is that, the exception is thrown, but not catched. And the program says:
Error inserting nombre=blabla edad=25 idPaciente=1
android.database.SQLiteConstraintException: error code 19: constraint failed
I know that it's something about the duplication on the primary key, but I wanna do so!
Flo, thanky you for your answer, but yes, I created the table, but what I didn't post, is that I have a method for erasing all databases and then creating them again whenever I press a button like this:
db.execSQL(DROP_TABLE_HISTORIAL);
db.execSQL(DROP_TABLE_MEDICO);
db.execSQL(DROP_TABLE_CONF);
db.execSQL(DROP_TABLE_PACIENTE);
So yes, I'm sure. But what Sarmand answered works for me, so thank you for your help :-)
Sorry, but I can't vote... Don't have enough points >_<
If you want to duplicate primary key then dont declare it as primary key. Do it like this
CREATE TABLE IF NOT EXISTS PACIENTE(idPaciente INTEGER , ....);

Categories

Resources