Android get all row from table and sent to server - android

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

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

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

CursorOutofBoundsException Index -1 requested with size of 0

I have a database called updateparty from which i have to create a array list of type hashmap string.When i try to retrieve data from db,the cursor does not move to next record.
Here is the code for db insertion.
for (int i = 0; i < poslist.size(); i++) {
SQLiteDatabase db7 = db.getWritableDatabase();
ContentValues values5= new ContentValues();
values5.put(DBManager.TableInfo.KEYID, ID1);
values5.put(DBManager.TableInfo.DOCU, document);
values5.put(DBManager.TableInfo.ATTEND,attendancelist.get(i));
values5.put(DBManager.TableInfo.EMAIL, emaillist.get(i));
values5.put(DBManager.TableInfo.PARTY,partytypelist.get(i) );
values5.put(DBManager.TableInfo.BIO,biometriclist.get(i));
values5.put(DBManager.TableInfo.KEY_LOGIN_USER,username2);
String condition5 = DBManager.TableInfo.DOCU + " =?";
Cursor cursor5 = db7.query(DBManager.TableInfo.UPDATEPARTY, null, condition5, new String[]{DBManager.TableInfo.ATTEND}, null, null, null);
long status5 = db7.insert(DBManager.TableInfo.UPDATEPARTY, null, values5);
System.out.println( "Parties insert : " + status5);
cursor5.close();
db7.close();
}
Code to create arraylist from above db:
public ArrayList<HashMap<String, String>>getPartypost(DBOperation db) {
ArrayList<HashMap<String, String>> listParties11 = new ArrayList<HashMap<String, String>>();
try {
String query = "select * from " + DBManager.TableInfo.UPDATEPARTY + " where " + DBManager.TableInfo.KEY_LOGIN_USER + " = '" + GenericMethods.email + "'";
System.out.println("query:"+query);
SQLiteDatabase sqlite1 = db.getWritableDatabase();
Cursor c = sqlite1.rawQuery(query, null);
while(c.moveToNext()) {
HashMap<String, String> selectiondetails10 = new HashMap<String, String>();
System.out.println("value:"+c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("document_id", c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("att_id", c.getString(c.getColumnIndex(DBManager.TableInfo.ATTEND)));
selectiondetails10.put("email", c.getString(c.getColumnIndex(DBManager.TableInfo.EMAIL)));
selectiondetails10.put("party_type", c.getString(c.getColumnIndex(DBManager.TableInfo.PARTY)));
selectiondetails10.put("biometric", c.getString(c.getColumnIndex(DBManager.TableInfo.BIO)));
selectiondetails10.put("exec_email", c.getString(c.getColumnIndex(DBManager.TableInfo.KEY_LOGIN_USER)));
listParties11.add(selectiondetails10);
}
closeCursor(c);
//}
// }
System.out.println("list size:"+listParties11.size());
} catch (Exception e) {
// TODO: handle exception.
e.printStackTrace();
}
db.close();
return listParties11;
}
This is the error message:
What i need is to create a arraylist from this db
change your insertion code to this:
SQLiteDatabase db7 = db.getWritableDatabase();
ContentValues values5= new ContentValues();
for (int i = 0; i < poslist.size(); i++) {
values5.put(DBManager.TableInfo.KEYID, ID1);
values5.put(DBManager.TableInfo.DOCU, document);
values5.put(DBManager.TableInfo.ATTEND,attendancelist.get(i));
values5.put(DBManager.TableInfo.EMAIL, emaillist.get(i));
values5.put(DBManager.TableInfo.PARTY,partytypelist.get(i) );
values5.put(DBManager.TableInfo.BIO,biometriclist.get(i));
values5.put(DBManager.TableInfo.KEY_LOGIN_USER,username2);
String condition5 = DBManager.TableInfo.DOCU + " =?";
Cursor cursor5 = db7.query(DBManager.TableInfo.UPDATEPARTY, null, condition5, new String[]{DBManager.TableInfo.ATTEND}, null, null, null);
long status5 = db7.insert(DBManager.TableInfo.UPDATEPARTY, null, values5);
System.out.println( "Parties insert : " + status5);
cursor5.close();
db7.close();
}
Use following code , while loop should be like this:
while(!c.isAfterLast())
public ArrayList<HashMap<String, String>>getPartypost(DBOperation db) {
ArrayList<HashMap<String, String>> listParties11 = new ArrayList<HashMap<String, String>>();
try {
String query = "select * from " + DBManager.TableInfo.UPDATEPARTY + " where " + DBManager.TableInfo.KEY_LOGIN_USER + " = '" + GenericMethods.email + "'";
System.out.println("query:"+query);
SQLiteDatabase sqlite1 = db.getWritableDatabase();
Cursor c = sqlite1.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()) {
HashMap<String, String> selectiondetails10 = new HashMap<String, String>();
System.out.println("value:"+c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("document_id", c.getString(c.getColumnIndex(DBManager.TableInfo.DOCU)));
selectiondetails10.put("att_id", c.getString(c.getColumnIndex(DBManager.TableInfo.ATTEND)));
selectiondetails10.put("email", c.getString(c.getColumnIndex(DBManager.TableInfo.EMAIL)));
selectiondetails10.put("party_type", c.getString(c.getColumnIndex(DBManager.TableInfo.PARTY)));
selectiondetails10.put("biometric", c.getString(c.getColumnIndex(DBManager.TableInfo.BIO)));
selectiondetails10.put("exec_email", c.getString(c.getColumnIndex(DBManager.TableInfo.KEY_LOGIN_USER)));
listParties11.add(selectiondetails10);
c.moveToNext();
}
closeCursor(c);
//}
// }
System.out.println("list size:"+listParties11.size());
} catch (Exception e) {
// TODO: handle exception.
e.printStackTrace();
}
db.close();
return listParties11;
}

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 compare the value of sqlite table to the json tag value in android

I want to compare the value of the id in sqlite to the value of TAG_ID coming from the json webservice.I just stuck up to do this..
What I have tried so far is
class LoadAll extends AsyncTask<String, String, String>
{
protected String doInBackground(String... args)
{
Log.i("url ",url_all_products);
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",params);
Log.w("All book: ", json.toString());
Log.i(url_all_products, url_all_products);
try
{
System.err.println("json array "+json.getJSONArray(TAG_PRODUCTS));
bookProduct = json.getJSONArray(TAG_PRODUCTS);
}
catch (JSONException e)
{
e.printStackTrace();
}
if(data_exist!=bookProduct.length()){
Log.i("in update","m here");
Cursor cursors = getRawEvents("select id from bcuk_book");
try{
for (int i = 0; i < bookProduct.length(); i++) {
JSONObject c = bookProduct.getJSONObject(i);
String Bid = c.getString(TAG_ID);
ArrayList<String> mapId = new ArrayList<String>();
mapId.add(TAG_ID);
Log.e(Bid,Bid);
while(cursors.moveToNext())
{
System.err.println("update coded STEON"+cursors.getString(0));
Log.e(Bid,c.getString(TAG_ID));
}
}
}
catch(JSONException e){
e.printStackTrace();
}
}
else{
Log.i("Done good","m here");
}
return null;
}
The reason behind
if(data_exist!=bookProduct.length()){
this statement is the variable data_exist=cursor.getCount();
and the bookProduct.length is the length of the jsonarray I want to compare them if the length is not same then I want to update the new values into the sqlite.could any one suggest me the approach to do this
if the length is not same then I want to update the new values into
the sqlite.
Not a good way to update databases.
Suppose that there is some changes in the server database fields. Same count but the contents is different.
This is the way I do:
String sql = "select * from " + DB_TABLE + " where " + TAG_ID + "='" + id + "'";
Cursor c = database.rawQuery(sql, null);
c.moveToFirst();
if( c.getCount() > 0){ // already in the database
// update entry with TAG_ID = id
}
else{ // new entry
// add new entry
}

Categories

Resources