Multiple insert SQLite : data can't save - android

i am trying to insert multiple data into sqlite, i get data from server in json format, i parse the data from my activity. and trying to save into my database. But i wonder, how can i save data in sqlite multiple times?
I get some references and and check in my logcat everything is alright. How can I solve this? Thanks in advance
public List<ModelAgen> updateTaccessUser(){
List<ModelAgen> data = new ArrayList<ModelAgen>();
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
String update = "INSERT INTO taccesagen(" +
"id," +
"ref_magen," +
"ref_tuser," +
"def," +
"nama" +
")" +
" VALUES" +
"(?, ?, ?, ?, ?)";
for (int i = 0; i < data.size(); i++) {
String kondisi;
if (data.get(i).getDef() == "t") {
kondisi = "1";
} else {
kondisi = "0";
}
SQLiteStatement insert = db.compileStatement(update);
insert.bindLong(1, data.get(i).getId());
insert.bindString(2, data.get(i).getRef_magen());
insert.bindString(3, data.get(i).getRef_tuser());
insert.bindString(4, kondisi);
insert.bindString(5, data.get(i).getNama());
insert.execute();
}
db.setTransactionSuccessful();
}finally {
db.endTransaction();
}
return data;
}

You can insert multiple records like this way
try {
for(int i=0;i<lstModelAgen.size();i++) {
ContentValues contentValues = new ContentValues();
contentValues.put("column1", lstModelAgen.get(i).getcolumn1Value);
contentValues.put("column2", lstModelAgen.get(i).getcolumn2Value());
db.insert("taccesagen", null, contentValues);
}
} catch (Exception e) {
e.printStackTrace();
}

Try below
for (int i = 0; i < data.size(); i++) {
String kondisi;
if (data.get(i).getDef() == "t") {
kondisi = "1";
} else {
kondisi = "0";
}
ArrayList<ContentValues> arrvals = new ArrayList<ContentValues>();
ContentValues values = new ContentValues();
values.put("id", data.get(i).getId());
values.put("ref_magen", data.get(i).getRef_magen());
values.put("ref_tuser",data.get(i).getRef_tuser() );
values.put("def", kondisi);
values.put("nama", data.get(i).getNama());
arrvals.add(values);
}
db.InsertData("taccesagen", arrvals);

Related

Android SQLiteStatement Insert, nothing happen

i have some data from SoapObject, i want insert to sqlite, for better performance, i use the following code :
public void testInsert(String sql, SoapObject rs, int index) {
try {
sql = "INSERT INTO NSPMasterHarga (KdBarang, Wilayah, HargaJual1, HargaJual2) VALUES (?, ?, ?, ?)";
theDatabase = getWritableDatabase();
theDatabase.beginTransaction();
String drop = "DROP TABLE IF EXISTS NSPMasterHarga";
SQLiteStatement stmtDrop = theDatabase.compileStatement(drop);
stmtDrop.execute();
String create = "CREATE TABLE NSPMasterHarga (KdBarang TEXT PRIMARY KEY, Wilayah TEXT, HargaJual1 TEXT, HargaJual2 TEXT)";
SQLiteStatement stmtCreate = theDatabase.compileStatement(create);
stmtCreate.execute();
SQLiteStatement stmt = theDatabase.compileStatement(sql);
int count = rs.getPropertyCount();
for (int i = 0; i < count; i++) {
SoapObject row = (SoapObject) rs.getProperty(i);
for (int j = 1; j <= index; j++) {
stmt.bindString(j, row.getProperty(j - 1).toString().replace("anyType{}", ""));
}
long entryID = stmt.executeInsert();
stmt.clearBindings();
}
/*for (int i = 0; i < NUMBER_OF_ROWS; i++) {
//generate some values
stmt.bindString(1, randomName);
stmt.bindString(2, randomDescription);
stmt.bindDouble(3, randomPrice);
stmt.bindLong(4, randomNumber);
long entryID = stmt.executeInsert();
stmt.clearBindings();
}*/
theDatabase.setTransactionSuccessful();
theDatabase.endTransaction();
theDatabase.close();
}
catch (Exception ex)
{
String err = ex.getMessage();
}
}
When debug, i've got nothing error, but the data not insert to my sqlite.
Any idea or clue ?
Thanks
for better performance
I'm not so sure which part of the code you are referring to. Opening and closing the database after each interaction is terrible for performance. The SQLiteOpenHelper takes care of all this, so you don't need to do anything manually.
Try the following alternative to insert an entry:
public boolean addEntry(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("column1", "value1"); // make sure the type corresponds to your sql column type
values.put("column2", "value2");
values.put("column3", "value3");
values.put("column4Int", 1);
long newRowId = db.insert(TABLE_NAME, null, values);
Log.d("DBHelper", "Added row " + newRowId + " to DB.");
return newRowId != -1; // -1 means it failed
}

How do I use contentvalue for inserting (Custom)ARRAY list in SQlite?

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.

Insert JSON to SQLite table on Android

i have a JSONObject :
{"Table1":[{"row1":"1","B":"2"},{"row2":"1","B1":"2"}],"Table2":[{"C":"1","D":"1145"},{"C":"1","D":"1145"}],"Table3":[{"E":"62","F":"1"},{"C":"1","D":"1145"}]}
how can I insert into sqlite foreach table ?
now use this code:
for (Iterator<String> iterator = mJson.keys(); iterator.hasNext(); ) {
String tableName = iterator.next();
if (mJson.optJSONArray(tableName) != null) {
resetTable(tableName);
JSONArray tableArray = mJson.optJSONArray(tableName);
for (int i = 0; i < tableArray.length(); i++) {
JSONObject tableData = tableArray.getJSONObject(i);
ContentValues Values = new ContentValues();
for (Iterator<String> iter = tableData.keys(); iter.hasNext(); ) {
String key = iter.next();
Values.put(key, tableData.get(key).toString());
}
db.insert(tableName, null, Values);
}
}
}
but i want fastest and better way
Use bulk insert:
for (Iterator<String> iterator = mJson.keys(); iterator.hasNext(); ) {
String tableName = iterator.next();
if (mJson.optJSONArray(tableName) != null) {
resetTable(tableName);
String sql = "INSERT INTO " + tableName + " VALUES (?);";
SQLiteStatement statement = db.compileStatement(sql);
db.beginTransaction();
JSONArray tableArray = mJson.optJSONArray(tableName);
for (int i = 0; i < tableArray.length(); i++) {
JSONObject tableData = tableArray.getJSONObject(i);
for (Iterator<String> iter = tableData.keys(); iter.hasNext(); ) {
String key = iter.next();
statement.clearBindings();
statement.bindString(1,tableData.get(key).toString());
statement.execute();
}
}
db.setTransactionSuccessful();
db.endTransaction();
}
}
You can use ContentValues with beginTransaction into SQLite that is quite easy as well as faster then prepared statements
For this you have to create ContentValues Array previously or create Content values object into your loop. and pass into insert method .this solution solve your both of problem in one.
mDatabase.beginTransaction();
try {
for (ContentValues cv : values) {
long rowID = mDatabase.insert(table, " ", cv);
if (rowID <= 0) {
throw new SQLException("Failed to insert row into ");
}
}
mDatabase.setTransactionSuccessful();
count = values.length;
} finally {
mDatabase.endTransaction();
}
You can only pass Content Values Object like for loop and insert and in above code Transaction are used so it will speed up data base storage .

Getting specific value from Array which does not exist in database

I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !

Android Sqlite Transaction and Content Provider

I'm Parsing a JSON WebService and creating a array with data to INSERT and DELETE entries in a database.
I found the solution bulkInsert to insert multiple rows using database transactions inside a content provider, however, I am trying to do the same procedure to delete multiple lines.
The INSERT solution:
#Override
public int bulkInsert(Uri uri, ContentValues[] allValues) {
SQLiteDatabase sqlDB = mCustomerDB.getWritableDatabase();
int numInserted = 0;
String table = MyDatabase.TABLE;
sqlDB.beginTransaction();
try {
for (ContentValues cv : allValues) {
//long newID = sqlDB.insertOrThrow(table, null, cv);
long newID = sqlDB.insertWithOnConflict(table, null, cv, SQLiteDatabase.CONFLICT_REPLACE);
if (newID <= 0) {
throw new SQLException("Error to add: " + uri);
}
}
sqlDB.setTransactionSuccessful();
getContext().getContentResolver().notifyChange(uri, null);
numInserted = allValues.length;
} finally {
sqlDB.endTransaction();
}
return numInserted;
}
Using this call:
mContext.getContentResolver().bulkInsert(ProviderMyDatabase.CONTENT_URI, valuesToInsertArray);
Is there any way to delete multiple rows (with this array ID's) of database using content provider.
UPDATE:
I found this solution, using the `IN clause:
List<String> list = new ArrayList<String>();
for (ContentValues cv : valuesToDelete) {
Object value = cv.get(DatabaseMyDatabase.KEY_ROW_ID);
list.add(value.toString());
}
String[] args = list.toArray(new String[list.size()]);
String selection = DatabaseMyDatabase.KEY_ROW_ID + " IN(" + new String(new char[args.length-1]).replace("\0", "?,") + "?)";
int total = mContext.getContentResolver().delete(ProviderMyDatabase.CONTENT_URI, selection, args);
LOGD(TAG, "Total = " + total);
The problem is that, if the JSON return more than 1000 rows to insert, occurs error, because the SQLITE_MAX_VARIABLE_NUMBER is set to 999. It can be changed but only at compile time.
ERROR: SQLiteException: too many SQL variables
Thanks in advance
I solved this issue with this code:
if (!valuesToDelete.isEmpty()) {
StringBuilder sb = new StringBuilder();
String value = null;
for (ContentValues cv : valuesToDelete) {
value = cv.getAsString(kei_id);
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(value);
}
String args = sb.toString();
String selection = kei_id + " IN(" + args + ")";
int total = mContext.getContentResolver().delete(uri, selection, null);
LOGD(TAG, "Total = " + total);
} else {
LOGD(TAG, "No data to Delete");
}
Thanks
User ContentResolver object to delete multiple rows.
// get the ContentResolver from a context
// if not from any activity, then you can use application's context to get the ContentResolver
// 'where' is the condition e.g., "field1 = ?"
// whereArgs is the values in string e.g., new String[] { field1Value }
ContentResolver cr = getContentResolver();
cr.delete(ProviderMyDatabase.CONTENT_URI, where, whereArgs);
So any row with (field1 = field1Value) will be deleted.
If you want to delete all the rows then
cr.delete(ProviderMyDatabase.CONTENT_URI, "1 = 1", null);

Categories

Resources