Insert JSON to SQLite table on Android - 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 .

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 to insert an array to SQLite?

I need to insert an array loaded by JSON into an SQLite database. Any help is appreciated.
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray sites = jsonObj.getJSONArray("Sites");
for (int i = 0; i < sites.length(); i++) {
JSONObject c = sites.getJSONObject(i);
String id = c.getString("id");
String nam = c.getString("names");
String loc = c.getString("location");
HashMap<String, String> sit = new HashMap<>();
sit.put("id", id);
sit.put("names", name);
sit.put("location", loc);
array_sites.add(sit);
Try this:
public void addData(ArrayList<String> list){
int size = list.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, list.get(i));
Log.d("Data Inserted ",""+ cv);
db.insertOrThrow(TABLE_NAME, null, cv);
}
db.close();
}catch (Exception e){
Log.e("Exception>>>>", e + " ");
}
Call from where you store your data
addData(array_sites);
I suggested for ArrayList<String>, You can use your own ArrayList<YourDataType>.

Multiple insert SQLite : data can't save

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

How to GSON/JSON serialize an Android Cursor?

import android.database.Cursor;
Cursor myCursor = mContentResolver.query(uri, null,..)
String JSON = new Gson().toJson(myCursor, Cursor.class);
My string JSON equals an empty [] because myCursor doesn't get serialized properly.
Any suggestions?
private static JSONArray cur2Json(Cursor cursor) {
//http://stackoverflow.com/questions/13070791/android-cursor-to-jsonarray
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
final int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
int i;// = 0;
for ( i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
String getcol = cursor.getColumnName(i),
getstr = cursor.getString(i);
mLog.error("ColumnName(i):\t " + getcol + "\t: " + getstr);
rowObject.put(
getcol,
getstr
);
} catch (JSONException e) {
mLog.error( e.getMessage());
}
}
}//for
mLog.error("columns i:\t " + i + "\totalColumn:\t " + totalColumn);
resultSet.put(rowObject);
cursor.moveToNext();
}
return resultSet;
}//cur2Json
You can use this piece of code to convert 1 cursor data to GSON Object directly
column name will be used as the key
column value will be used as value
Map hashMap = new HashMap();
Gson gson = new Gson();
for (int i = 0; i < cursor.getColumnCount(); i++) {
hashMap.put(cursor.getColumnName(i),cursor.getString(i));
}
System.out.println(gson.toJson(hashMap));
If You want to convert multiple Cursor Element You can use a arrayList with Map and then serialise arraylist to String
Gson gson = new Gson();
ArrayList<Map> list = new ArrayList<>();
while (!cursor.isAfterLast()) {
Map hashMap = new HashMap();
for (int i = 0; i < cursor.getColumnCount(); i++) {
hashMap.put(cursor.getColumnName(i), cursor.getString(i));
}
list.add(hashMap);
cursor.moveToNext();
}
System.out.println("\t\t\t" + gson.toJson(list));

how to get the database value to a String array in android(sqlite Database)

I have a database name "CUED" (sqlite Android)it have a table HELLO which contain a column NAME I can get the value to String from that column.
Let me show you my code section
myDB =hello.this.openOrCreateDatabase("CUED", MODE_PRIVATE, null);
Cursor crs = myDB.rawQuery("SELECT * FROM HELLO", null);
while(crs.moveToNext())
{
String uname = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
}
It will print the value one by one. Now what I need is that I want to get the column values from database and so that I can store it in a String Array.
You already did the hard part... the array stuff is pretty simple:
String[] array = new String[crs.getCount()];
int i = 0;
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array[i] = uname;
i++;
}
Whatever, I always recommend to use collections in cases like this:
List<String> array = new ArrayList<String>();
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array.add(uname);
}
In order to compare the arrays, you can do things like this:
boolean same = true;
for(int i = 0; i < array.length; i++){
if(!array[i].equals(ha[i])){
same = false;
break;
}
}
// same will be false if the arrays do not have the same elements
String[] str= new String[crs.getCount()];
crs.movetoFirst();
for(int i=0;i<str.length();i++)
{
str[i] = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
crs.movetoNext();
}
Enjoy it
This is my code that returns arraylist contains afield value:
public ArrayList<String> getAllPlayers() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT " + serailnumber + " as _id, " + title
+ " from " + table, new String[] {});
ArrayList<String> array = new ArrayList<String>();
while (cur.moveToNext()) {
String uname = cur.getString(cur.getColumnIndex(title));
array.add(uname);
}
return array;
}

Categories

Resources