How to GSON/JSON serialize an Android Cursor? - android

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

Related

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

Android get all row from table and sent to server

I want to send all the row data present in one table to server, My table having three different data rows, But when I am using Cursor it add only last row data three time. So how to get all three rows
JSONObject putjsonObjectTrans = new JSONObject();
try {
int count = dbHelper.getCountOfRows();
JSONObject invoiceDetail = new JSONObject();
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
String query = "select * from " + TABLE_NAME;
JSONArray invoiceArray = new JSONArray();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
while (cursor.moveToNext())
{
/* for (int i = 0; i < count; i++)*/
invoiceDetail.put("ItemId", cursor.getInt(1));
invoiceDetail.put("ItemCode", cursor.getString(2));
invoiceDetail.put("ItemName", cursor.getString(3));
invoiceDetail.put("ItemQuantity", cursor.getDouble(4));
invoiceDetail.put("Rate", cursor.getDouble(5));
invoiceDetail.put("DiscAmount", cursor.getDouble(6));
invoiceDetail.put("DiscPercentage", cursor.getDouble(7));
invoiceArray.put(invoiceDetail);
}
putjsonObjectTrans.put("acc_no", acccNo);
putjsonObjectTrans.put("acc_name", accCustomerName);
putjsonObjectTrans.put("EntryType", getEntryTypeName);
putjsonObjectTrans.put("EntryDate", gSentryDAte);
putjsonObjectTrans.put("NetAmount",15.2);
putjsonObjectTrans.put("division_no", MainActivity.divisionID);
putjsonObjectTrans.put("invoicedtl", invoiceArray);
} catch (JSONException e) {
e.printStackTrace();
}
write below line inside while loop
JSONObject invoiceDetail = new JSONObject();
Change code to this
JSONObject putjsonObjectTrans = new JSONObject();
try {
int count = dbHelper.getCountOfRows();
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
String query = "select * from " + TABLE_NAME;
JSONArray invoiceArray = new JSONArray();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
while (cursor.moveToNext())
{
/* for (int i = 0; i < count; i++)*/
JSONObject invoiceDetail = new JSONObject();
invoiceDetail.put("ItemId", cursor.getInt(1));
invoiceDetail.put("ItemCode", cursor.getString(2));
invoiceDetail.put("ItemName", cursor.getString(3));
invoiceDetail.put("ItemQuantity", cursor.getDouble(4));
invoiceDetail.put("Rate", cursor.getDouble(5));
invoiceDetail.put("DiscAmount", cursor.getDouble(6));
invoiceDetail.put("DiscPercentage", cursor.getDouble(7));
invoiceArray.put(invoiceDetail);
}
putjsonObjectTrans.put("acc_no", acccNo);
putjsonObjectTrans.put("acc_name", accCustomerName);
putjsonObjectTrans.put("EntryType", getEntryTypeName);
putjsonObjectTrans.put("EntryDate", gSentryDAte);
putjsonObjectTrans.put("NetAmount",15.2);
putjsonObjectTrans.put("division_no", MainActivity.divisionID);
putjsonObjectTrans.put("invoicedtl", invoiceArray);
} catch (JSONException e) {
e.printStackTrace();
}

JSON data arraylist and sqlite data arraylist compared to each other after compare data not same after inserted in sqlite database in android

JSON data stored in ArrayList and Sqlite Data Stored Also Another Arraylist. THis Two Database Compare to Each other.in Json Arraylist only New Updated data Stored in Database.JSON and sqlite database data not same after stored in sqlite database. or give me some easy way to JSON data stored in sqlite database.
MainActivity
try
{
JSONArray jsonArray = new JSONArray(s);
if(jsonArray != null){
for (int i = 0; i < 1 ;i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
StudentName = jsonObject.getString("StudentName");
RollNo = jsonObject.getDouble("RollNo");
Standard = jsonObject.getString("Standard");
Division = jsonObject.getString("Division");
FatherNo = jsonObject.getDouble("SMSNo");
Address = jsonObject.getString("Std_Address");
School = jsonObject.getString("SchoolName");
Image = jsonObject.getString("ImagePath");
StdID = jsonObject.getLong("stdid");
DivID = jsonObject.getLong("DivisionID");
String date = jsonObject.getString("DOB");
String replaceDate = date.replace("/Date(", "").replace(")/", "");
Long getDate = Long.valueOf(replaceDate);
DOB = dateFormat.format(getDate);
HashMap<String, String> map = new HashMap<String, String>();
// map.put("Id", cursor.getString(0));
map.put("UserName", StudentName);
map.put("DOB", DOB);
map.put("RollNo", String.valueOf(RollNo));
map.put("STD", Standard);
map.put("DIV", Division);
map.put("MobileNO", String.valueOf(FatherNo));
map.put("Address", Address);
map.put("School", School);
jsonList = new ArrayList<>();
jsonList.add(map);
}
DBHelper db = new DBHelper(getApplicationContext());
ArrayList<HashMap<String,String>> list = db.getAllRegistrationData();
for (int j = 0; j< jsonList.size(); j++ ){
for (int k = 0; k < list.size(); k++){
if (jsonList.get(j).equals(list.get(k))){
Toast.makeText(Registration_Activity.this, "Alredy exist", Toast.LENGTH_SHORT).show();
}else {
long id = db.insertRegistration(StudentName,RollNo,Standard,Division,FatherNo,Address,School,DOB);
Toast.makeText(Registration_Activity.this, "Insert id : " + id, Toast.LENGTH_SHORT).show();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
DBHelper
public ArrayList<HashMap<String,String>> getAllRegistrationData(){
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+TABLE_REGISTRATION,null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("UserName", cursor.getString(1));
map.put("DOB", cursor.getString(2));
map.put("RollNo", cursor.getString(3));
map.put("STD", cursor.getString(4));
map.put("DIV", cursor.getString(5));
map.put("MobileNO", cursor.getString(6));
map.put("Address", cursor.getString(7));
map.put("School", cursor.getString(8));
list.add(map);
} while (cursor.moveToNext());
}
return list;
}

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 .

How to get values from ArrayList using 2 for loops

This is the class where I try to add elements from cursor to ArrayList.
public ArrayList<String> getArrayList()
{
int i;
sdb=this.getReadableDatabase();
c=null;
ArrayList<String> list=null;
try{
c=sdb.rawQuery("select * from Products", null);
c.moveToFirst();
if(c!=null)
{
list=new ArrayList<String>();
do
{
for(i=1;i<=c.getColumnCount();i++)
{
list.add(c.getString(c.getColumnIndex("ProductName")));
list.add(c.getString(c.getColumnIndex("ProduceType")));
list.add(c.getString(c.getColumnIndex("Company")));
list.add(c.getString(c.getColumnIndex("Price")));
list.add(c.getString(c.getColumnIndex("Quantity")));
}
}while(c.moveToNext());
}
else
System.out.println("c null");
}catch(Exception e)
{
e.printStackTrace();
//c=null;
}
/*finally{
if(c!=null && !c.isClosed())
{
c.close();
c=null;
}
close();
}*/
return list;
}
This is where I try to retrieve data from ArrayList and add them to expandablelistview.I want the 1st column of every row in cursor in the group view and the remaining columns of the corresponding row in child view.
private void loadData(){
db=new DatabaseHelper(this);
//db.open();
System.out.println("returned from db.open() in loadData");
ArrayList<String> al=db.getArrayList();
db.close();
int count=al.size();
int i,j;
try{
for(i=1;i<=count;i=i+5)
{
String pn=al.get(i);
for(j=i;j<=i+5;j++)
{
String inf=al.get(j);
addProduct(pn,inf);
}
}
}catch(StackOverflowError e)
{
e.printStackTrace();
}
}
I am going wrong with the for loop as of my knowledge.Logcat is showing the following error
07-04 02:44:14.747: E/CursorWindow(1881): Failed to read row 0, column -1 from a CursorWindow which has 3 rows, 5 columns.
Please tell me the correct usage of arraylist data retrieval.Thanks in advance.
I would suggest going with this approach, as the approach you are using is a bad practice.
Instead of having List of String, use an object of a custom class called ProductInfo, (which include all these Strings), and add and retrieve data from that List.
public class ProductInfo{
String productName, productType, company, price, quantity;
//getter setter
}
// add data
List<ProductInfo> productList = new ArrayList<ProductInfo>();
Cursor c = null;
do {
for (int i = 1; i <= c.getColumnCount(); i++) {
ProductInfo pInfo = new ProductInfo();
pInfo.setProductName(c.getString(c
.getColumnIndex("ProductName")));
pInfo.setProductType(c.getString(c
.getColumnIndex("ProduceType")));
pInfo.setCompany(c.getString(c.getColumnIndex("Company")));
pInfo.setPrice(c.getString(c.getColumnIndex("Price")));
pInfo.setQuantity(c.getString(c.getColumnIndex("Quantity")));
productList.add(pInfo);
}
} while (c.moveToNext());
// retrieve data
for (int i = 0; i < productList.size(); i++) {
System.out.println("Info of Product "+(i+1));
ProductInfo pInfo = productList.get(i);
System.out.println("Prod name: "+ pInfo.getProductName());
System.out.println("Prod Type: "+pInfo.getProductType());
System.out.println("Company: "+pInfo.getCompany());
System.out.println("Price: "+pInfo.getPrice());
System.out.println("Quantity: "+pInfo.getQuantity());
}
Try this way,hope this will help you to solve your problem.
public ArrayList<HashMap<String, String>> getArrayList() {
int i;
sdb = this.getReadableDatabase();
c = null;
ArrayList<HashMap<String, String>> list = null;
try {
c = sdb.rawQuery("select * from Products", null);
c.moveToFirst();
if (c != null) {
list = new ArrayList<HashMap<String, String>>();
do {
for (i = 1; i <= c.getColumnCount(); i++) {
HashMap<String, String> row = new HashMap<String, String>();
row.put("ProductName", c.getString(c.getColumnIndex("ProductName")));
row.put("ProduceType", c.getString(c.getColumnIndex("ProduceType")));
row.put("Company", c.getString(c.getColumnIndex("Company")));
row.put("Price", c.getString(c.getColumnIndex("Price")));
row.put("Quantity", c.getString(c.getColumnIndex("Quantity")));
list.add(row);
}
} while (c.moveToNext());
} else
System.out.println("c null");
} catch (Exception e) {
e.printStackTrace();
//c=null;
}
/*finally{
if(c!=null && !c.isClosed())
{
c.close();
c=null;
}
close();
}*/
return list;
}
private void loadData() {
db = new DatabaseHelper(this);
//db.open();
System.out.println("returned from db.open() in loadData");
ArrayList<HashMap<String, String>> al = db.getArrayList();
db.close();
int count = al.size();
int i, j;
try {
for (HashMap<String, String> product : al) {
System.out.println("ProductName: " + product.get("ProductName"));
System.out.println("ProduceType: " + product.get("ProduceType"));
System.out.println("Company: " + product.get("Company"));
System.out.println("Price: " + product.get("Price"));
System.out.println("Quantity: " + product.get("Quantity"));
}
} catch (StackOverflowError e) {
e.printStackTrace();
}
}

Categories

Resources