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
}
Related
I've been trying to make an SQLite database which creates a new table every year automatically with the name along the lines of abc_2018. The problem is that every time a new table has to be added (i.e. the year changes) I need to update the DATABASE_VERSION. This probably requires storage of the current DATABASE_VERSION and incrementing its value every time a new table has to be added. I tried using SharedPreferences but I keep getting random errors.
So my question is how do I make a mechanism that automatically creates a table when the user's system date changes, or more precisely, when a new year starts?
EDIT
Solved my problem by doing this:
try {
cur = db.query(TABLE_NAME, PROJECTION, SELECTION, ARGS, null, null, null);
} catch (SQLiteException e) {
if (e.getMessage().contains("no such table")){
// create new table and execute query
}
}
Instead of :-
try {
cur = db.query(TABLE_NAME, PROJECTION, SELECTION, ARGS, null, null, null);
} catch (SQLiteException e) {
if (e.getMessage().contains("no such table")){
// create new table and execute query
}
}
Regarding the potential issues as pointed out by pskink's comment:-
if (e.getMessage().contains("no such table")) no no no, its so ugly
workaround that i dont know what to say... what if they change it to
"No such table" someday? or "that table does not exist"?
The following would be more resilient (considering how SQLite caters for backwards compatibility) :-
cur = db.query(sqlite_master,new String{"tbl_name"},"tbl_name=?",new String[]{TABLE_NAME},null,null,null);
if (cur.getCount < 1) { // ==0 if you prefer
//Create new table
}
You can use broadcast receiver like ACTION_DATE_CHANGED
More details can be found at https://developer.android.com/reference/android/content/Intent.html#ACTION_DATE_CHANGED
Code:
public void createDynamicDatabase(Context context,String tableName,ArrayList<String> title) {
Log.i("INSIDE createLoginDatabase() Method","*************creatLoginDatabase*********");
try {
int i;
String queryString;
myDataBase = context.openOrCreateDatabase("Db",Context.MODE_WORLD_WRITEABLE, null); //Opens database in writable mode.
//System.out.println("Table Name : "+tableName.get(0));
queryString = title.get(0)+" VARCHAR(30),";
Log.d("**createDynamicDatabase", "in oncreate");
for(i = 1; i < title.size() - 1; i++)
{
queryString += title.get(i);
queryString +=" VARCHAR(30)";
queryString +=",";
}
queryString+= title.get(i) +" VARCHAR(30)";
queryString = "CREATE TABLE IF NOT EXISTS " + tableName + "("+queryString+");";
System.out.println("Create Table Stmt : "+ queryString);
myDataBase.execSQL(queryString);
} catch (SQLException ex) {
Log.i("CreateDB Exception ",ex.getMessage());
}
}
public void insert(Context context,ArrayList<String> array_vals,ArrayList<String> title,String TABLE_NAME) {
Log.d("Inside Insert","Insertion starts for table name: "+TABLE_NAME);
myDataBase = context.openOrCreateDatabase("Db",Context.MODE_WORLD_WRITEABLE, null); //Opens database in writable mode.
String titleString=null;
String markString= null;
int i;
titleString = title.get(0)+",";
markString = "?,";
Log.d("**createDynamicDatabase", "in oncreate");
for(i = 1; i < title.size() - 1; i++)
{
titleString += title.get(i);
titleString +=",";
markString += "?,";
}
titleString+= title.get(i);
markString += "?";
//System.out.println("Title String: "+titleString);
//System.out.println("Mark String: "+markString);
INSERT="insert into "+ TABLE_NAME + "("+titleString+")"+ "values" +"("+markString+")";
System.out.println("Insert statement: "+INSERT);
//System.out.println("Array size iiiiii::: "+array_vals.size());
//this.insertStmt = this.myDataBase.compileStatement(INSERT);
int s=0;
while(s<array_vals.size()){
System.out.println("Size of array1"+array_vals.size());
//System.out.println("Size of array"+title.size());
int j=1;
this.insertStmt = this.myDataBase.compileStatement(INSERT);
for(int k =0;k< title.size();k++)
{
//System.out.println("Value of column "+title+" is "+array_vals.get(k+s));
//System.out.println("PRINT S:"+array_vals.get(k+s));
System.out.println("BindString: insertStmt.bindString("+j+","+ array_vals.get(k+s)+")");
insertStmt.bindString(j, array_vals.get(k+s));
j++;
}
s+=title.size();
}
insertStmt.executeInsert();
}
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);
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 .
I'm trying to copy all the data in a database table, which correspond to the WHERE clause, and insert them into another table. I'm trying this code, but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why?
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String sql = "SELECT data, unita_di_misura FROM prev WHERE numero ='"+numero_ricevuto+"'";
Cursor c = db.rawQuery(sql, null);
int count = c.getCount();
String[] data = new String[count];
String[] unita_di_misura = new String[count];
for(int i=0; i<count; i++) {
c.moveToNext();
data[i] = c.getString(0);
unita_di_misura[i] = c.getString(1);
}
for(int i=0 ;i < data.length;i++){
ContentValues cv = new ContentValues();
cv.put(VerTable.SI_NO, "0");
cv.put(VerTable .DATA, data[i]);
cv.put(VerTable .U_M, e.unita_di_misura[i]);
db.insert(VerTable .TABLE_NAME, null, cv);
}
c.close();
db.close();
}
Try this 3 line solution hope this will help you
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String sql = "INSERT INTO "+VerTable .TABLE_NAME+" SELECT 0,data, unita_di_misura FROM prev WHERE numero = '"+numero_ricevuto+"'";
db.execSQL(sql);
db.close();
}
but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why?
Possibly you ran the code more than once.
Also, pulling data from db only to insert it back is not very efficient. It's better to let the database engine do the work for you, e.g.
db.execSQL("INSERT INTO " + VerTable.TABLE_NAME +
"(" + VerTable.SI_NO + "," VerTable.DATA + "," + VerTable.U_M + ") " +
"SELECT 0, data, unita_di_misura FROM prev WHERE numero=?",
new String[] { numero_ricevuto });
Using ? params also avoids the possiblity of string SQL injection.
I have fileds list & values list.I want to insert records using DBAdapter.I tried from this link http://mfarhan133.wordpress.com/2010/10/24/database-crud-tutorial-for-android/
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(Insert.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
initialValues.put("name", etName.getText().toString());
initialValues.put("age", etAge.getText().toString());
long n = dbAdapter.insertRecordsInDB("user", null, initialValues);
Toast.makeText(Insert.this, "new row inserted with id = " + n, Toast.LENGTH_SHORT).show();
Please anybody help me how to send the fields & their values at runtime.Please help me as soon as possible
You can make fields as String array & their value also make array.For example:
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
for (int k = 0; k < names.length(); k++) {
strToFields[k] = names.getString(k);
strToFieldsVal[k]=strVal;
}
calling method like
insertTableRecords(actualtable, strToFields, strToFieldsVal);
method should be:
public void insertTableRecords(String strTableName, String[] strToFields, String[] strValues){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.insertRecordsInDB(strTableName, null, initialValues);
System.out.println( " -- inserted status : --- " + n);
}
If you need more help see this Android sqlite dynamic insert query