I am using an array to send data to my SQLite Database.
The array contains all the selected values.
private void addContacts(String[] selectedItems) {
manager.Insert_phone_contact(selectedItems);
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
My SQLite databse code to insert the above mentioned "selectedItems" array in contentvalues is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
for(int i=0;i<contact.length;i++){
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
DB.close();
}
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
Only the first array item is stored in ContentValues cv, not all the array elements.
What's wrong in this code?
How can I insert all the array items in the "TABLE_CONTACTS" table?
Any help will be appreciated.
You have to fix few lines of code, First is to delete Db.Close() and add it after loop
The code you were trying was closing the Db object after first insertion and unavailable for the rest of loop iterations.
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues(); //Declare once
for(int i=0;i<contact.length;i++){
cv.put(CONTACT_NAME, contact[i]);
DB.insert(TABLE_CONTACTS, null, cv); //Insert each time for loop count
}
DB.close(); // Now close the DB Object
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
You will need to move insert and close statement outside for loop because currently you are storing only one value and not opening db again :
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
cv.put(CONTACT_NAME, contact[i]);
}
DB.insert(TABLE_CONTACTS, null, cv); // insert in db
DB.close(); // call close
You can also consider transactions in sqlite
DB.beginTransaction();
for(int i=0;i<contact.length;i++){
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, contact[i]);
DB.insert(TABLE_CONTACTS, "0.0", cv);
}
DB.setTransactionSuccessful();
DB.endTransaction();
This will make insert operation faster than single insert
you can using code i have just some changes your code.
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
for(int i=0;i<contact.length;i++){
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}
cv.close();
DB.close();
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
Related
ERROR- am getting as type mistmatch.
Here is my code-Please help
public void addDetailDescription(List<Detail> detailList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < detailList.size(); i++) {
Log.e("vlaue inserting==", "" + detailList.get(i));
values.put(DETAIL_ID, String.valueOf(detailList.get(i)));
values.put(COLUMN_HEADING, String.valueOf(detailList.get(i)));
values.put(COLUMN_IMAGE_DETAIl, String.valueOf(detailList.get(i)));
values.put(COLUMN_DETAIL, String.valueOf(detailList.get(i)));
values.put(DETAIL_DESCRIPTION_ID, String.valueOf(detailList.get(i)));
}
db.insert(DESCRIPTION_DETAIL_TABLE, null, values);
db.close();
}
I think you have to write a function like this and in a for cycle ,call this function for each item of list.
public long SaveUsers(Users users) {
long id = -1;
ContentValues contentValues = null;
try {
contentValues = new ContentValues();
contentValues.put("name", users.getName());
contentValues.put("email", users.getEmail());
contentValues.put("phone", users.getPhone());
contentValues.put("password", users.getPassword());
db=sqliteHelper.getWritableDatabase();
id = db.insert(SqliteHelper.TABLE_USERS, null, contentValues);
} catch (Exception e) {
Log.d("Database Insert","Exception:"+e.getMessage());
} finally {
if(db!=null && db.isOpen())
db.close();
}
return id;
}
In your code, contentValue change every time and finally just the last item will be inserted to database and it's completely wrong.
I want to check if there are already 5 rows in my database, but I can't use the execSQL method to call SELECT because it returns void and nothing else seems to fit in an if statement. So is there a simple fix or do I have to go about this another way?
//add a new row to the database
public void addProduct(Products product){
SQLiteDatabase db = this.getWritableDatabase();
if(db.execSQL("SELECT Count * FROM " + TABLE_PRODUCTS) == 5){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
}
Try this
SQLiteDatabase db = this.getReadableDatabase();
if(DatabaseUtils.queryNumEntries(db, TABLE_PRODUCTS) == 5){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
db.insert(TABLE_PRODUCTS, null, values); db.close();
}
I'm familiar with Oracle SQL/PL, but not with SQLite, I have managed to construct my database, with an addition operation. I was however wondering how I could implement a WHERE condition for adding data later on to a specific row.
Here is my addition code:
public void putInformation(DatabaseOperations dop, String name, String pass, String email){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME,null, cv);
Log.d("Database Operations", "One Raw Inserted");
}
I think you are looking for an UPDATE query:
public void updateInformation(DatabaseOperations dop, String name, String pass, String email){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.update(TableData.TableInfo.TABLE_NAME, cv, TableData.TableInfo.USER_NAME+"=?",new String[]{name});
Log.d("Database Operations", k+" Rows Updated");
}
SQLiteDatabase.update docs
WHERE condition for adding data later on to a specific row. If I understand correctly then it will be update for sqlite database. For that you can refer below code.
public void updateInformation(DatabaseOperations dop, String name, String pass, String email){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long index = SQ.update(TableData.TableInfo.TABLE_NAME, cv, TableData.TableInfo.USER_NAME+"=?", new String[] {name});
}
You can't use WHERE condition on insert query. WHERE condition for adding data later on to a specific row. For this you can use UPDATE query.
LINKS:
http://www.tutorialspoint.com/sqlite/sqlite_update_query.htm
http://android-er.blogspot.in/2011/06/edit-row-in-sqlite-database-using.html
Im trying to seed my sqlite database with testdata in onCreate method in my SqliteOpenHelper... However, it doesn't matter why I try it still won't work.. Im getting getDatabase called recursively.
This is the code of my SqliteOpenHelper class..
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(SQL_CREATE_CONTACT);
SeedData();
} catch (SQLException e) {
Log.d("ContactDbHelper", "Create Database failed" + e.getMessage());
}
}
private void SeedData() {
db = getWritableDatabase();
Contact contact = new Contact("Test1", "CEO/Founder", "http://test.se/system/data/6816/medium/test1.jpg", "blalblalblalblalblalbalbalallbalabalalbalb");
// Create ContentValues
ContentValues contentValues = new ContentValues();
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_NAME, contact.getName());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_PROFESSION, contact.getProfession());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_URL, contact.getUrl());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_DESCRIPTION, contact.getDescription());
// Insert values into Contact table rows
db.insert(
ContactContract.Contact.TABLE_NAME,
null,
contentValues
);
Contact contact2 = new Contact("Test2", "Employee", "http://test2.se/system/data/6816/medium/test2.jpg", "asdadsadadadadasdasdadsasds");
// Create ContentValues
ContentValues contentValues2 = new ContentValues();
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_NAME, contact.getName());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_PROFESSION, contact.getProfession());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_URL, contact.getUrl());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_DESCRIPTION, contact.getDescription());
// Insert values into Contact table rows
db.insert(
ContactContract.Contact.TABLE_NAME,
null,
contentValues2
);
}
Is there any other way to insert multiple rows with data, or any other approach to seed? I don't like plain sql-queries, I still wanna use SqliteDatabase db.insert()
I also tried creating custom Insert method and called it form SeedData method but got recursive error again:
// Create
public long Insert(Contact contact){
db = getWritableDatabase();
// Create ContentValues
ContentValues contentValues = new ContentValues();
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_NAME, contact.getName());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_PROFESSION, contact.getProfession());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_URL, contact.getUrl());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_DESCRIPTION, contact.getDescription());
// Insert values into Contact table rows
long contactId = db.insert(
ContactContract.Contact.TABLE_NAME,
null,
contentValues);
// Return generated id from database
return contactId;
}
Don't use db = getWritableDatabase();. This is causing the looping.
Pass SQLiteDatabase as an argument to SeedData(SQLiteDatabase db) in onCreate method
Hello I'm using this code to insert data into my database. In another activity I use a Cursor and I can see the data of table1 or table2 individually. But if I use both I can only see the data of table 2.
When I use the cursors to get the data I see that one is empty. I think I'm not inserting the data correctly.
What am I doing wrong?
ContentValues cv=new ContentValues();
//TABLE 1
cv.put(idAttendance, 1);
cv.put(attendPlayer, "Tiago");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 2);
cv.put(attendPlayer, "Joao");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 3);
cv.put(attendPlayer, "Pedro");
db.insert(AttendanceTable, idAttendance, cv);
//TABLE2
cv.put(idTrainInd, 1);
cv.put(TIindicator, "Remate Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
cv.put(idTrainInd, 2);
cv.put(TIindicator, "Remate SEM Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
Still can't save data.
My Class is something like this:
public class DatabaseHelper extends SQLiteOpenHelper {
private ... // database and tables
public DatabaseHelper(Context context) {
super(context, dbName, null,33);
}
SQLiteDatabase db = null;
#Override
public void onCreate(SQLiteDatabase db) {
//here i create all tables
db.execSQL("CREATE TABLE ... )
db=this.getWritableDatabase();
//THEN I USE THE CODE OF MY FIRST QUESTION
ContentValues cv=new ContentValues();
//TABLE 1
cv.put(idAttendance, 1);
cv.put(attendPlayer, "Tiago");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 2);
cv.put(attendPlayer, "Joao");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 3);
cv.put(attendPlayer, "Pedro");
db.insert(AttendanceTable, idAttendance, cv);
//TABLE2
//TABLE2
cv.put(idTrainInd, 1);
cv.put(TIindicator, "Remate Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
cv.put(idTrainInd, 2);
cv.put(TIindicator, "Remate SEM Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
//THEN I USE THIS TO RETURN GET THE DATA BUT TABLE TWO IS STILL EMPTY
/**Get all players from local database*/
public Cursor getPlayers() {
// db = this.getReadableDatabase();
Cursor c=db.rawQuery("SELECT player FROM Attendancetabl", null);
//c.close();
return c;
}
/**Get all players from local database*/
public Cursor getIndicadors() {
// db = this.getReadableDatabase();
Cursor c=db.rawQuery("SELECT indicator FROM TrainingIndicador", null);
//c.close();
return c;
}
It's the same problem of the first question.
Try to use support code:
private void insertData(SQLiteDatabase base, String table, String columnHack, ContentValues values) {
base.beginTransaction();
base.insertWithOnConflict(table, columnHack, values, SQLiteDatabase.CONFLICT_REPLACE);
base.setTransactionSuccessful();
base.endTransaction();
}
Then just call instead your db.insert this one code:
insertData(db, TrainingIndicatorTable, idTrainInd, cv);
Piece of code to Content Values insert will be like below.
private ContentValues initialValues;
initialValues = new ContentValues();
initialValues.put("User_ID", User_ID);
initialValues.put("FirstName", FirstName);
initialValues.put("LastName", LastName);
initialValues.put("UserID", UserID));
initialValues.put("Password",Password1);
initialValues.put("Email", Email);
mydb.insertTitle(initialValues,"CheckLogin");
// this will be you databse class or method to insert the values. hope this helps you.