Android SYNCHRONIZATION with SQL mgmt studio using JSON - android
I am creating project for hotel to take orders in android.
In that i have to synchronize data(i am here using web-service for generating results) of sqlite of (tablet) and sqlstudio 2008 which is on server.
I am using json for it. But i want to know how to do it in Eclipse.Here is that code which is used to call web service.and while debuging it with TABLET it is showing me Error of PROCESS STOP UNEXPECTEDLY(android.process.acore)
public class JSONServices {
public static final Boolean CallService = true;
JSONHelper json = new JSONHelper();
public String MissedQueriesCount = "0";
// Function to Login A User
public SW_Login Login(String UserId, String Password) {
SW_Login loginwrapper = new SW_Login();
JSONObject jObject = new JSONObject();
if (CallService == true) {
jObject = json.getHttpJson(JSONServiceURL.Login(UserId, Password));
} else // For Test Purpose
{
String jsonString = "{\"Service\":\"Login\",\"ResultSet\":[{\"Status\":\"1\",\"UserId\":\"21\",\"Token\":\"VJgueUxYCNaN6JGk\",\"Errorcode\":\"\",\"Errordesc\":\"\"}]}";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONArray retData = GetJSONArray(jObject, "ResultSet");
loginwrapper.Status = GetJSONElement(retData, "Status", 0);
loginwrapper.UserId = GetJSONElement(retData, "UserId", 0);
loginwrapper.Token = GetJSONElement(retData, "Token", 0);
loginwrapper.ErrCode = GetJSONElement(retData, "Errorcode", 0);
loginwrapper.ErrDesc = GetJSONElement(retData, "Errordesc", 0);
return loginwrapper;
}
// Function to Get Tables
public List<SW_Table> GetTables(String AreaId) {
JSONObject jObject = new JSONObject();
if (CallService == true) {
if (AreaId == "0") {
String strURL = JSONServiceURL.GetAllOpenOrderTables();
jObject = json.getHttpJson(strURL);
} else {
jObject = json.getHttpJson(JSONServiceURL.GetTables(AreaId));
}
} else // For Test Purpose
{
String jsonString = "{ \"ResFrom\": \"gettables\", \"ResultSet\": [ { \"AreaID\": 1, \"TableID\": 2, \"TableDesc\": \"Table 1\", \"Status\": null, \"Errorcode\": null, \"Errordesc\": null }, { \"AreaID\": 1, \"TableID\": 4, \"TableDesc\": \"Table 1\", \"Status\": null, \"Errorcode\": null, \"Errordesc\": null } ] }";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
List<SW_Table> tablewrappers = new ArrayList<SW_Table>();
JSONArray retData = GetJSONArray(jObject, "ResultSet");
if (retData != null) {
for (int counter = 0; counter <= retData.length() - 1; counter++) {
SW_Table tablewrapper = new SW_Table();
tablewrapper.Status = GetJSONElement(retData, "Status", counter);
tablewrapper.AreaID = GetJSONElement(retData, "AreaID", counter);
tablewrapper.TableID = GetJSONElement(retData, "TableID",
counter);
tablewrapper.TableDesc = GetJSONElement(retData, "TableDesc",
counter);
tablewrapper.ErrCode = GetJSONElement(retData, "Errorcode",
counter);
tablewrapper.ErrDesc = GetJSONElement(retData, "Errordesc",
counter);
tablewrappers.add(tablewrapper);
}
}
return tablewrappers;
}
// Function to Get Order Details
public List<SW_OrderDetails> GetOrderDetails(String Mode, String TableName) {
JSONObject jObject = new JSONObject();
if (CallService == true) {
jObject = json.getHttpJson(JSONServiceURL.GetOrderDetails(Mode,
TableName));
} else // For Test Purpose
{
String jsonString = "{ \"ResFrom\": \"getorderdetails\", \"ResultSet\": [ { \"OrderID\": 7, \"OrderDevice\": \"Reception\", \"OrderIP\": \"\", \"OrderTable\": \"Table 1_1\", \"OrderDate\": \"\", \"OrderStatus\": null, \"SendPing\": \"\", \"PaymentMode\": \"\", \"CreditNumber\": \"\", \"DebitNumber\": \"\", \"CancellationReason\": \"\", \"OrderNo\": 0, \"OrderAmount\": 50.0, \"CustId\": 0, \"OrderItems\": [ { \"OrderID\": 7, \"ItemID\": 405, \"Quantity\": 2.0, \"Remarks\": \"Cold\", \"Price\": 15.0, \"Discount\": 0.0, \"SaleTax\": 0.0, \"ItemName\": \"Coffee\", \"ItemTypeId\": 47 } ], \"Status\": \"S1\", \"Errorcode\": null, \"Errordesc\": null } ] }";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
List<SW_OrderDetails> orderwrappers = new ArrayList<SW_OrderDetails>();
JSONArray retData = GetJSONArray(jObject, "ResultSet");
if (retData != null) {
for (int counter = 0; counter <= retData.length() - 1; counter++) {
SW_OrderDetails orderwrapper = new SW_OrderDetails();
orderwrapper.Status = GetJSONElement(retData, "Status", counter);
orderwrapper.OrderID = GetJSONElement(retData, "OrderID",
counter);
orderwrapper.OrderTable = GetJSONElement(retData, "OrderTable",
counter);
orderwrapper.OrderStatus = GetJSONElement(retData,
"OrderStatus", counter);
orderwrapper.OrderAmount = GetJSONElement(retData,
"OrderAmount", counter);
orderwrapper.ItemTypeId = GetJSONElement(retData, "ItemTypeId",
counter);
JSONArray retItemData = GetJSONArray(jObject, "OrderItems");
for (int itemcounter = 0; itemcounter <= retItemData.length() - 1; itemcounter++) {
SW_ItemDetails itemwrapper = new SW_ItemDetails();
itemwrapper.ItemID = GetJSONElement(retData, "ItemID",
counter);
itemwrapper.ItemName = GetJSONElement(retData, "ItemName",
counter);
itemwrapper.Quantity = GetJSONElement(retData, "Quantity",
counter);
itemwrapper.Remarks = GetJSONElement(retData, "Remarks",
counter);
orderwrapper.ItemDetails.add(itemwrapper);
}
orderwrapper.ErrCode = GetJSONElement(retData, "Errorcode",
counter);
orderwrapper.ErrDesc = GetJSONElement(retData, "Errordesc",
counter);
orderwrappers.add(orderwrapper);
}
}
return orderwrappers;
}
// Function to Get Order Details
public List<SW_ItemDetails> GetTableOrderDetails(String Mode, String TableId) {
JSONObject jObject = new JSONObject();
if (CallService == true) {
jObject = json.getHttpJson(JSONServiceURL.GetTableOrderDetails(
Mode, TableId));
} else // For Test Purpose
{
String jsonString = "{ \"ResFrom\": \"gettableorder\", \"ResultSet\": [ { \"OrderID\": 3, \"ItemID\": 403, \"Quantity\": 1, \"Remarks\": \"\", \"Price\": 35.0, \"Discount\": 0.0, \"SaleTax\": 0.0, \"ItemName\": \"Hot Chocolate\", \"ItemTypeId\": 47, \"Status\": null, \"Errorcode\": null, \"Errordesc\": null }, { \"OrderID\": 3, \"ItemID\": 405, \"Quantity\": 2, \"Remarks\": \"Cold\", \"Price\": 15.0, \"Discount\": 0.0, \"SaleTax\": 0.0, \"ItemName\": \"Coffee\", \"ItemTypeId\": 47, \"Status\": null, \"Errorcode\": null, \"Errordesc\": null } ] }";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
List<SW_ItemDetails> itemDetails = new ArrayList<SW_ItemDetails>();
JSONArray retData = GetJSONArray(jObject, "ResultSet");
if (retData != null) {
SW_ItemDetails itemwrappertemp = new SW_ItemDetails();
itemwrappertemp.Status = GetJSONElement(retData, "Status", 0);
if (itemwrappertemp.Status.toString().trim().equals("0")) {
return null;
}
for (int counter = 0; counter <= retData.length() - 1; counter++) {
SW_ItemDetails itemwrapper = new SW_ItemDetails();
itemwrapper.ItemID = GetJSONElement(retData, "ItemID", counter);
itemwrapper.ItemName = GetJSONElement(retData, "ItemName",
counter);
itemwrapper.Quantity = GetJSONElement(retData, "Quantity",
counter);
itemwrapper.Remarks = GetJSONElement(retData, "Remarks",
counter);
itemwrapper.ItemTypeId = GetJSONElement(retData, "ItemTypeId",
counter);
itemwrapper.Status = GetJSONElement(retData, "Status", counter);
itemwrapper.ErrCode = GetJSONElement(retData, "Errorcode",
counter);
itemwrapper.ErrDesc = GetJSONElement(retData, "Errordesc",
counter);
itemDetails.add(itemwrapper);
}
}
return itemDetails;
}
public void SaveOrder(String TableId, List<JSONObject> jsonarray) {
try {
Map<String, String> kvPairs = new HashMap<String, String>();
kvPairs.put("orderdetails", jsonarray.toString());
// Normally I would pass two more JSONObjects.....
if (CallService == true) {
HttpResponse re = json.doPost(JSONServiceURL
.SaveOrderDetails(TableId.toString().trim()), kvPairs);
String temp = EntityUtils.toString(re.getEntity());
if (temp.compareTo("SUCCESS") == 0) {
// Toast.makeText(this, "Sending complete!",
// Toast.LENGTH_LONG).show();
}
} else // For Test Purpose
{
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Function to Get Areas
public List<SW_Area> GetAreas() {
JSONObject jObject = new JSONObject();
if (CallService == true) {
jObject = json.getHttpJson(JSONServiceURL.SyscArea());
} else // For Test Purpose
{
String jsonString = "{ \"ResFrom\": \"syncarea\", \"ResultSet\": [ { \"AreaId\": 1, \"AreaDesc\": \"Area 1\", \"Status\": null, \"Errorcode\": null, \"Errordesc\": null }, { \"AreaId\": 2, \"AreaDesc\": \"Area 2\", \"Status\": null, \"Errorcode\": null, \"Errordesc\": null }, { \"AreaId\": 3, \"AreaDesc\": \"Area 3\", \"Status\": null, \"Errorcode\": null, \"Errordesc\": null } ] }";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
List<SW_Area> areawrappers = new ArrayList<SW_Area>();
JSONArray retData = GetJSONArray(jObject, "ResultSet");
if (retData != null) {
for (int counter = 0; counter <= retData.length() - 1; counter++) {
SW_Area areawrapper = new SW_Area();
areawrapper.Status = GetJSONElement(retData, "Status", counter);
areawrapper.AreaID = GetJSONElement(retData, "AreaId", counter);
areawrapper.AreaDesc = GetJSONElement(retData, "AreaDesc",
counter);
areawrapper.ErrCode = GetJSONElement(retData, "Errorcode",
counter);
areawrapper.ErrDesc = GetJSONElement(retData, "Errordesc",
counter);
areawrappers.add(areawrapper);
}
}
return areawrappers;
}
// Function to Get Table
public List<SW_Table> GetTables() {
JSONObject jObject = new JSONObject();
if (CallService == true) {
jObject = json.getHttpJson(JSONServiceURL.SyncTable());
} else // For Test Purpose
{
String jsonString = "{ \"ResFrom\": \"synctable\", \"ResultSet\": [ { \"AreaId\": 1, \"TableId\":1.1 , \"TableDesc\": null, \"Errorcode\": null, \"Errordesc\": null }, { \"AreaId\": 2, \"TableId\":2.1\": \"TableDesc\":null,\"Status\": null, \"Errorcode\": null, \"Errordesc\": null }, { \"AreaId\": 3, \"TableId\":2.1\"TableDesc\": 3\", \"Status\": null, \"Errorcode\": null, \"Errordesc\": null } ] }";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
List<SW_Table> areawrappers = new ArrayList<SW_Table>();
JSONArray retData = GetJSONArray(jObject, "ResultSet");
if (retData != null) {
for (int counter = 0; counter <= retData.length() - 1; counter++) {
SW_Table areawrapper = new SW_Table();
areawrapper.Status = GetJSONElement(retData, "Status", counter);
areawrapper.AreaID = GetJSONElement(retData, "AreaId", counter);
areawrapper.TableID = GetJSONElement(retData, "TableID",
counter);
areawrapper.TableDesc = GetJSONElement(retData, "TableDesc",
counter);
areawrapper.ErrCode = GetJSONElement(retData, "Errorcode",
counter);
areawrapper.ErrDesc = GetJSONElement(retData, "Errordesc",
counter);
areawrappers.add(areawrapper);
}
}
return areawrappers;
}
// Function to Get ItemType
public List<SW_ItemType> GetItemTypes() {
JSONObject jObject = new JSONObject();
if (CallService == true) {
jObject = json.getHttpJson(JSONServiceURL.SyncItemType());
} else // For Test Purpose
{
String jsonString = "{ \"ResFrom\": \"syncitemtype\", \"ResultSet\": [ {\"Status\":null, \"ItemTypeId\": 1, \"ItemTypeName\":Cold Drinks \"ItemTypeDesc\": null, \"ItemTypeCode\": null, \"Discount\":30,\"SalesTax\":12.50,\"Flag\":null,\"ImageIndex\":null,\"Errorcode\": null, \"Errordesc\": null },{\"Status\":null,\"ItemTypeId\": 2, \"ItemTypeName\":MainCourse,\"ItemTypeDesc\": null, \"ItemTypeCode\": null, \"Discount\":25,\"SalesTax\":12.50,\"Flag\":null,\"ImageIndex\":null,\"Errorcode\": null, \"Errordesc\": null } ] }";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
List<SW_ItemType> areawrappers = new ArrayList<SW_ItemType>();
JSONArray retData = GetJSONArray(jObject, "ResultSet");
if (retData != null) {
for (int counter = 0; counter <= retData.length() - 1; counter++) {
SW_ItemType areawrapper = new SW_ItemType();
areawrapper.Status = GetJSONElement(retData, "Status", counter);
areawrapper.ItemTypeId = GetJSONElement(retData, "ItemTypeId", counter);
areawrapper.ItemTypeName = GetJSONElement(retData, "ItemTypeName", counter);
areawrapper.ItemTypeDesc = GetJSONElement(retData, "ItemTypeDesc", counter);
areawrapper.ItemTypeCode = GetJSONElement(retData, "ItemTypeCode", counter);
areawrapper.Discount = GetJSONElement(retData, "Discount",counter);
areawrapper.SalesTax = GetJSONElement(retData, "SalesTax",counter);
areawrapper.Flag = GetJSONElement(retData, "Flag",counter);
areawrapper.ImageIndex = GetJSONElement(retData, "ImageIndex",counter);
areawrapper.ErrCode = GetJSONElement(retData, "ErrCode",counter);
areawrapper.ErrDesc = GetJSONElement(retData, "ErrDesc",counter);
areawrappers.add(areawrapper);
}
}
return areawrappers;
}
// Function to Get Item
public List<SW_Item> GetItems() {
JSONObject jObject = new JSONObject();
if (CallService == true) {
jObject = json.getHttpJson(JSONServiceURL.SyscArea());
} else // For Test Purpose
{
String jsonString = "{ \"ResFrom\": \"syncitem\", \"ResultSet\": [ { \"Status\": 1, \"ItemId\":1, \"ItemTypeId\":2,\"ItemName\":Jaljira,\"ItemDesc\":null,\"Price\":20,\"Active\":null,\"ItemCode\":null, \"Errorcode\": null, \"Errordesc\": null },{ \"Status\": 1, \"ItemId\":2, \"ItemTypeId\":3,\"ItemName\":NimbuPani,\"ItemDesc\":null,\"Price\":15,\"Active\":null,\"ItemCode\":null, \"Errorcode\": null, \"Errordesc\": null } ] }";
try {
jObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
List<SW_Item> areawrappers = new ArrayList<SW_Item>();
JSONArray retData = GetJSONArray(jObject, "ResultSet");
if (retData != null) {
for (int counter = 0; counter <= retData.length() - 1; counter++) {
SW_Item areawrapper = new SW_Item();
areawrapper.Status = GetJSONElement(retData, "Status", counter);
areawrapper.ItemId = GetJSONElement(retData, "ItemId", counter);
areawrapper.ItemTypeId = GetJSONElement(retData, "ItemTypeId",counter);
areawrapper.ItemName = GetJSONElement(retData, "ItemName", counter);
areawrapper.ItemDesc = GetJSONElement(retData, "ItemDesc", counter);
areawrapper.Price = GetJSONElement(retData, "Price", counter);
areawrapper.Active = GetJSONElement(retData, "Active", counter);
areawrapper.ItemCode = GetJSONElement(retData, "ItemCode", counter);
areawrapper.ErrCode = GetJSONElement(retData, "Errorcode",counter);
areawrapper.ErrDesc = GetJSONElement(retData, "Errordesc",counter);
areawrappers.add(areawrapper);
}
}
return areawrappers;
}
private String Encrypt(String password) {
String toEnc = password; // Value to encrypt
MessageDigest mdEnc = null;
try {
mdEnc = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Encryption algorithm
mdEnc.update(toEnc.getBytes(), 0, toEnc.length());
String md5 = new BigInteger(1, mdEnc.digest()).toString(16);
if (md5.length() < 32)
md5 = "0" + md5;
return md5;
}
/* **************************************** */
/* Private Methods To Extract JSON Contents */
/* **************************************** */
private JSONArray GetJSONArray(JSONObject obj, String arrayName) {
JSONArray retData = null;
try {
retData = obj.getJSONArray(arrayName);
} catch (JSONException e) {
e.printStackTrace();
}
return retData;
}
private String GetJSONElement(JSONArray jsonArr, String Element, int index) {
String element = "";
try {
element = jsonArr.getJSONObject(index).getString(Element)
.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return element;
}
private String GetJSONString(JSONObject jObj, String Element) {
String element = "";
try {
element = jObj.getString(Element).toString();
} catch (JSONException e) {
e.printStackTrace();
}
return element;
}
private JSONObject GetJSONObject(JSONArray jsonArr, int index) {
JSONObject retData = null;
try {
retData = jsonArr.getJSONObject(index);
} catch (JSONException e) {
e.printStackTrace();
}
return retData;
}
}
Related
onPostExecute() seems to be called only once
I've created class which extends AsyncTask, to synchronize with service. After synchro is finished I want to put the time (hh:mm) into TextView, to inform user, when synchro was made last time. I am doing it inside onPostExecute(). Problem is that this happens only once. TextView doesn't get updated later. I'm prettey sure doInBackground() is being called because it takes quite a long time to synchronize just like when application starts (there is a lot of records), but I can't be 100% sure since data collection doesn't change at all. That's my AsyncTask class: private class Reconnect extends AsyncTask<String, Void, Void>{ private RotateAnimation anim = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f); #Override protected void onPreExecute() { rlRefresh.setEnabled(false); anim.setInterpolator(new LinearInterpolator()); anim.setRepeatCount(Animation.INFINITE); anim.setDuration(700); refreshIV.startAnimation(anim); } #Override protected Void doInBackground(String... strings) { retrofit2.Call<List<ServiceTaskAxapta>> call = api.getTasks("1", strings[0]); retrofit2.Response<List<ServiceTaskAxapta>> response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } if(response.code() != 200){ Toast.makeText(context, "Error 1", Toast.LENGTH_SHORT).show(); } else { for (int i = 0; i < response.body().size(); i++){ String endTime = DateParser.increaseTimeString(response.body().get(i).getReportTime(), 8, 0, false, null, null, null); allTasksDB.insertIntoDB(response.body().get(i).getTaskID(), "path", response.body().get(i).getStreet(), response.body().get(i).getCity(), response.body().get(i).getPhoneNumber(), response.body().get(i).getCompanyName(), Integer.parseInt(response.body().get(i).getReportDay()), Integer.parseInt(response.body().get(i).getReportMonth()), Integer.parseInt(response.body().get(i).getReportYear()), Integer.parseInt(response.body().get(i).getDeadlineDay()), Integer.parseInt(response.body().get(i).getDeadlineMonth()), Integer.parseInt(response.body().get(i).getDeadlineYear()), response.body().get(i).getReportTime(), endTime); } } call = api.getTasks("2", strings[0]); response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } if(response.code() != 200){ Toast.makeText(context, "Error 2", Toast.LENGTH_SHORT).show(); } else { for (int i = 0; i < response.body().size(); i++){ String endTime = DateParser.increaseTimeString(response.body().get(i).getStartTimeMax(), 24, 0,false, null, null, null); acceptedTasksDB.insertIntoDB(response.body().get(i).getTaskID(), "path", response.body().get(i).getStreet(), response.body().get(i).getCity(), response.body().get(i).getPhoneNumber(), response.body().get(i).getCompanyName(), Integer.parseInt(response.body().get(i).getDeadlineDay()), Integer.parseInt(response.body().get(i).getDeadlineMonth()), Integer.parseInt(response.body().get(i).getDeadlineYear()), Integer.parseInt(response.body().get(i).getAcceptedDay()), Integer.parseInt(response.body().get(i).getAcceptedMonth()), Integer.parseInt(response.body().get(i).getAcceptedYear()), response.body().get(i).getStartTime(), endTime, response.body().get(i).getStartTimeMax(), false, false, null, null); } } call = api.getTasks("3", strings[0]); response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } if(response.code() != 200){ Toast.makeText(context, "Error 3", Toast.LENGTH_SHORT).show(); } else { for (int i = 0; i < response.body().size(); i++){ acceptedTasksDB.insertIntoDB(response.body().get(i).getTaskID(), "path", response.body().get(i).getStreet(), response.body().get(i).getCity(), response.body().get(i).getPhoneNumber(), response.body().get(i).getCompanyName(), Integer.parseInt(response.body().get(i).getDeadlineDay()), Integer.parseInt(response.body().get(i).getDeadlineMonth()), Integer.parseInt(response.body().get(i).getDeadlineYear()), Integer.parseInt(response.body().get(i).getAcceptedDay()), Integer.parseInt(response.body().get(i).getAcceptedMonth()), Integer.parseInt(response.body().get(i).getAcceptedYear()), response.body().get(i).getStartTime(), null, response.body().get(i).getStartTimeMax(), true, false, null, null); } } call = api.getTasks("4", strings[0]); response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } if(response.code() != 200){ Toast.makeText(context, "Error 4", Toast.LENGTH_SHORT).show(); } else { for (int i = 0; i < response.body().size(); i++){ acceptedTasksDB.insertIntoDB(response.body().get(i).getTaskID(), "path", response.body().get(i).getStreet(), response.body().get(i).getCity(), response.body().get(i).getPhoneNumber(), response.body().get(i).getCompanyName(), Integer.parseInt(response.body().get(i).getDeadlineDay()), Integer.parseInt(response.body().get(i).getDeadlineMonth()), Integer.parseInt(response.body().get(i).getDeadlineYear()), Integer.parseInt(response.body().get(i).getAcceptedDay()), Integer.parseInt(response.body().get(i).getAcceptedMonth()), Integer.parseInt(response.body().get(i).getAcceptedYear()), response.body().get(i).getStartTime(), null, response.body().get(i).getStartTimeMax(), true, true, null, null); } } call = api.getTasks("5", strings[0]); response = null; try { response = call.execute(); } catch (IOException e) { e.printStackTrace(); } if(response.code() != 200){ Toast.makeText(context, "Error 5", Toast.LENGTH_SHORT).show(); } else { dbConnectionProblems.open(); for (int i = 0; i < response.body().size(); i++){ acceptedTasksDB.insertIntoDB(response.body().get(i).getTaskID(), "path", response.body().get(i).getStreet(), response.body().get(i).getCity(), response.body().get(i).getPhoneNumber(), response.body().get(i).getCompanyName(), Integer.parseInt(response.body().get(i).getDeadlineDay()), Integer.parseInt(response.body().get(i).getDeadlineMonth()), Integer.parseInt(response.body().get(i).getDeadlineYear()), Integer.parseInt(response.body().get(i).getAcceptedDay()), Integer.parseInt(response.body().get(i).getAcceptedMonth()), Integer.parseInt(response.body().get(i).getAcceptedYear()), response.body().get(i).getStartTime(), null, response.body().get(i).getStartTimeMax(), true, false, null, null); dbConnectionProblems.insertIntoDB(response.body().get(i).getTaskID(), true, null, null, null, null); } dbConnectionProblems.close(); } return null; } #Override protected void onPostExecute(Void aVoid) { if(!anim.hasEnded()){ refreshIV.setAnimation(null); } String lastSynchro = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + "#" + calendar.get(Calendar.DAY_OF_MONTH) + "-" + (calendar.get(Calendar.MONTH)-1) + "-" + calendar.get(Calendar.YEAR); ProjectStuff.saveLastSynchro(lastSynchro, context); String synchroTime = "Last synchro: " + DateParser.parseTime(context, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)); tvSynchroInfo.setText(synchroTime); rlRefresh.setEnabled(true); } } And the execute() method: rlRefresh.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { Reconnect refreshEvent = new Reconnect(); refreshEvent.execute("12"); } }); After amount of time (needed to synchronize), amination stops, so it looks like onPostExecute() is called, and TextView is updated, but every later call doesn't update it.
Ok, I've found the problem. I called calendar = Calendar.getInstance() inside onCreate() method, I should have done this in onPostExecute() right before saving it, and showing it inside TextView to get right time.
How to update the Recylerview View items after displayed First Json URL In android
I having a problem update the Item in Recycler View.I will explain clearly about my problem. I am using two Json URL's first Json URL can send the items to model class. after completed this called the adapter, then update the second Json URL items with the adapter by using setter model class. so that's why called adapter.notifyitemchanged, but only one time can updated items next time while looping doesn't update the items display empty for second time. Code: public void servicecallsingle(String list, final int pin) { url = Constants.singleproducturl + list; JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () { #Override public void onResponse(JSONObject response) { JSONObject response1 = response; if (response1 != null) { // int status=jsonObject.optInt("status"); String status = response1.optString("status"); if (status.equalsIgnoreCase("200")) { //check the status 200 or not try { productpath = response1.getString("productPath"); } catch (JSONException e) { e.printStackTrace(); } try { JSONObject responses = response1.getJSONObject("response"); jsonarray = responses.getJSONArray(DATA); if (jsonarray.length() > 0) { // looping through json and adding to movies list for (int i = 0; i < jsonarray.length(); i++) { item = new CartItemoriginal(); JSONObject product = jsonarray.getJSONObject(i); cartpid = product.getString("product_id"); cartproductname = product.getString("product_name"); cartaliasname = product.getString("product_alias"); cartprice = product.getString("mrp_price"); String sp = product.getString("selling_price"); String op = product.getString("offer_selling_price"); sellerid = product.getString("seller_id"); JSONArray pimg = product.getJSONArray("product_images"); JSONObject firstimg = pimg.getJSONObject(0); cartimg = firstimg.getString("original_res"); String[] img2 = cartimg.split("\\."); String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1]; String Quantity = product.getString("product_max_add"); String minqty = product.getString("product_min_add"); int qty = Integer.parseInt(Quantity); /*** calculation ***/ Long tsLong = System.currentTimeMillis() / 1000; String ts = tsLong.toString(); int ts1 = Integer.parseInt(ts); String startdate1 = product.getString("offer_selling_start_date"); String endate1 = product.getString("offer_selling_end_date"); if (("".equals(startdate1)) && ("".equals(endate1))) { // Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show(); if (cartprice.equalsIgnoreCase(sp)) { double d = Double.parseDouble(cartprice); int mrp = (int) d; price = String.valueOf(mrp); } else { double s = Double.parseDouble(sp); int sales = (int) s; price = String.valueOf(sales); } } else { int startdate = Integer.parseInt(startdate1); int endate2 = Integer.parseInt(endate1); if (ts1 > startdate && ts1 < endate2) { double offer = Double.parseDouble(op); int offers = (int) offer; price = String.valueOf(offers); } else { if (cartprice.equalsIgnoreCase(sp)) { double d = Double.parseDouble(cartprice); int mrp = (int) d; price = String.valueOf(mrp); } else { double s = Double.parseDouble(sp); int sales = (int) s; price = String.valueOf(sales); } } } item.setProductname(cartproductname); item.setQty(1); item.setProductimg(imagone); item.setMaxquantity(Quantity); item.setAliasname(cartaliasname); item.setPrice(price); item.setMinquantity(minqty); item.setProductid(cartpid); cart.add(item); // cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid)); } } } catch (JSONException e) { e.printStackTrace(); } } // condtion check the status 200 else // this is if status falied in runtime { Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show(); } // llm = new LinearLayoutManager(CartItems.this); MainLinear.setVisibility(View.VISIBLE); final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false); recyleitems.setHasFixedSize(false); recyleitems.setLayoutManager(layoutManager); cartadapter = new CartlistAdapter(cart, CartItems.this); Log.i(String.valueOf(cartadapter), "cartadapter"); recyleitems.setAdapter(cartadapter); recyleitems.setNestedScrollingEnabled(false); myView.setVisibility(View.GONE); cartadapter.notifyDataSetChanged(); } String id = cartpid; String selleid = sellerid; final int pinnum = pin; String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum; JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () { #Override public void onResponse(JSONObject responsesecond) { JSONObject response2 = responsesecond; // do something with response1 & response here... if (response2 != null) { // int status=jsonObject.optInt("status"); String status = response2.optString("status"); if (status.equalsIgnoreCase("200")) { //check the status 200 or not try { JSONObject responses = response2.getJSONObject("response"); jsonarray = responses.getJSONArray(DATA); if (jsonarray.length() > 0) { Log.i(String.valueOf(jsonarray.length()), "message"); // looping through json and adding to movies list for (int j = 0; j < jsonarray.length(); j++) { JSONObject product = jsonarray.getJSONObject(j); process = product.getString("process"); Message = product.getString("message"); if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) { cartdelivery = product.getString("delivery"); cartshippingcharge = product.getString("shipping_charge"); String pincode = product.getString("pincode"); /**************************calculation of shipping days**************************/ int day = Integer.parseInt(cartdelivery); Calendar c = Calendar.getInstance(); String dayNumberSuffix = getDayNumberSuffix(day); SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy"); String currentDateandTime = sdf.format(new Date()); try { c.setTime(sdf.parse(currentDateandTime)); } catch (ParseException e) { e.printStackTrace(); } c.add(Calendar.DATE, day); Date resultdate = new Date(c.getTimeInMillis()); currentDateandTime = sdf.format(resultdate); Log.d(String.valueOf(currentDateandTime), "shipping days"); cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime); cart.get(j).setShippincharge(cartshippingcharge); cart.get(j).setSellername("richard feloboune"); cartadapter.notifyItemChanged(j); cartadapter.notifyItemRangeChanged(j, cart.size()); } else { // cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum))); cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum)); cartadapter.notifyItemChanged(j); } } } } catch (JSONException e) { e.printStackTrace(); } // stopping swipe refresh // swipeRefreshLayout.setRefreshing(false); } // condtion check the status 200 else // this is if status falied in runtime { Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show(); } } pincheck(); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Log.i("onErrorResponse", error.toString()); } }); AppController.getInstance().addToRequestQueue(request2); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Log.i("onErrorResponse", error.toString()); } }); AppController.getInstance().addToRequestQueue(request1); } Note: While looping first time can set the item in setter model class but second couldn't set the item to model class. Anyone solve this problem glad to appreciate. Thanks in advance
The problem is volley doesn't wait for the request to be completed. So as the first call is made within seconds other call will be also made. So, you need to create an interface which will be called when the first webservice is called, and than in interface call other webservice and than notifyDataSet. public void servicecallsingle(String list, final int pin) { url = Constants.singleproducturl + list; JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () { #Override public void onResponse(JSONObject response) { JSONObject response1 = response; if (response1 != null) { // int status=jsonObject.optInt("status"); String status = response1.optString("status"); if (status.equalsIgnoreCase("200")) { //check the status 200 or not try { productpath = response1.getString("productPath"); } catch (JSONException e) { e.printStackTrace(); } parseJson(response1, new WebServiceCallBack{ public void getWebserviceCallBack(){ // Call another webservice here String id = cartpid; String selleid = sellerid; final int pinnum = pin; String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum; JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () { #Override public void onResponse(JSONObject responsesecond) { JSONObject response2 = responsesecond; // do something with response1 & response here... if (response2 != null) { // int status=jsonObject.optInt("status"); String status = response2.optString("status"); if (status.equalsIgnoreCase("200")) { //check the status 200 or not try { JSONObject responses = response2.getJSONObject("response"); jsonarray = responses.getJSONArray(DATA); if (jsonarray.length() > 0) { Log.i(String.valueOf(jsonarray.length()), "message"); // looping through json and adding to movies list for (int j = 0; j < jsonarray.length(); j++) { JSONObject product = jsonarray.getJSONObject(j); process = product.getString("process"); Message = product.getString("message"); if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) { cartdelivery = product.getString("delivery"); cartshippingcharge = product.getString("shipping_charge"); String pincode = product.getString("pincode"); /**************************calculation of shipping days**************************/ int day = Integer.parseInt(cartdelivery); Calendar c = Calendar.getInstance(); String dayNumberSuffix = getDayNumberSuffix(day); SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy"); String currentDateandTime = sdf.format(new Date()); try { c.setTime(sdf.parse(currentDateandTime)); } catch (ParseException e) { e.printStackTrace(); } c.add(Calendar.DATE, day); Date resultdate = new Date(c.getTimeInMillis()); currentDateandTime = sdf.format(resultdate); Log.d(String.valueOf(currentDateandTime), "shipping days"); cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime); cart.get(j).setShippincharge(cartshippingcharge); cart.get(j).setSellername("richard feloboune"); cartadapter.notifyItemChanged(j); cartadapter.notifyItemRangeChanged(j, cart.size()); } else { // cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum))); cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum)); cartadapter.notifyItemChanged(j); } } } } catch (JSONException e) { e.printStackTrace(); } // stopping swipe refresh // swipeRefreshLayout.setRefreshing(false); } // condtion check the status 200 else // this is if status falied in runtime { Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show(); } } pincheck(); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Log.i("onErrorResponse", error.toString()); } }); AppController.getInstance().addToRequestQueue(request2); } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Log.i("onErrorResponse", error.toString()); } }); AppController.getInstance().addToRequestQueue(request1); }); } } // condtion check the status 200 else // this is if status falied in runtime { Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show(); } // llm = new LinearLayoutManager(CartItems.this); MainLinear.setVisibility(View.VISIBLE); final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false); recyleitems.setHasFixedSize(false); recyleitems.setLayoutManager(layoutManager); cartadapter = new CartlistAdapter(cart, CartItems.this); Log.i(String.valueOf(cartadapter), "cartadapter"); recyleitems.setAdapter(cartadapter); recyleitems.setNestedScrollingEnabled(false); myView.setVisibility(View.GONE); cartadapter.notifyDataSetChanged(); } public void parseJson(JSONObject response1, WebServiceCallBack webserviceCallBack){ try { JSONObject responses = response1.getJSONObject("response"); jsonarray = responses.getJSONArray(DATA); if (jsonarray.length() > 0) { // looping through json and adding to movies list for (int i = 0; i < jsonarray.length(); i++) { item = new CartItemoriginal(); JSONObject product = jsonarray.getJSONObject(i); cartpid = product.getString("product_id"); cartproductname = product.getString("product_name"); cartaliasname = product.getString("product_alias"); cartprice = product.getString("mrp_price"); String sp = product.getString("selling_price"); String op = product.getString("offer_selling_price"); sellerid = product.getString("seller_id"); JSONArray pimg = product.getJSONArray("product_images"); JSONObject firstimg = pimg.getJSONObject(0); cartimg = firstimg.getString("original_res"); String[] img2 = cartimg.split("\\."); String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1]; String Quantity = product.getString("product_max_add"); String minqty = product.getString("product_min_add"); int qty = Integer.parseInt(Quantity); /*** calculation ***/ Long tsLong = System.currentTimeMillis() / 1000; String ts = tsLong.toString(); int ts1 = Integer.parseInt(ts); String startdate1 = product.getString("offer_selling_start_date"); String endate1 = product.getString("offer_selling_end_date"); if (("".equals(startdate1)) && ("".equals(endate1))) { // Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show(); if (cartprice.equalsIgnoreCase(sp)) { double d = Double.parseDouble(cartprice); int mrp = (int) d; price = String.valueOf(mrp); } else { double s = Double.parseDouble(sp); int sales = (int) s; price = String.valueOf(sales); } } else { int startdate = Integer.parseInt(startdate1); int endate2 = Integer.parseInt(endate1); if (ts1 > startdate && ts1 < endate2) { double offer = Double.parseDouble(op); int offers = (int) offer; price = String.valueOf(offers); } else { if (cartprice.equalsIgnoreCase(sp)) { double d = Double.parseDouble(cartprice); int mrp = (int) d; price = String.valueOf(mrp); } else { double s = Double.parseDouble(sp); int sales = (int) s; price = String.valueOf(sales); } } } item.setProductname(cartproductname); item.setQty(1); item.setProductimg(imagone); item.setMaxquantity(Quantity); item.setAliasname(cartaliasname); item.setPrice(price); item.setMinquantity(minqty); item.setProductid(cartpid); cart.add(item); // cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid)); } } } catch (JSONException e) { e.printStackTrace();} webserviceCallBack.getWebserviceCallBack(); } public interface WebServiceCallBack{ public void getWebserviceCallBack() }
how to resolve error in reading json?
Below is my json, which I am trying to read (code Log.i("callinfo", callInfo + ""); onwards, but getting error. My code to read and error message are also mentioned. { "CallInfo":[ { "ItemInfo":[ { "chargeable":"True", "itemID":"B13984350K" }, { "chargeable":"True", "itemID":"B13984351A" } ], "numberOfCopies":2 } ], "ISBN":[ "" ], "TitleAvailabilityInfo":null, "author":"Chief Army Medical Officer.", "baseCallNumber":"RC87.1 PRE", "publisherName":"HQ Army Medical Services,", "title":"Preventing heat injuries : the commanders' guide", "titleID":9206, "yearOfPublication":"2000" } Code: public void readBarCode(String response, String scannedBarcode) { final CountDownLatch latch = new CountDownLatch(1); final String[] names = new String[4]; JSONArray mArray, mArray1, mArray2; int totalCount = 0; int avail = 0; String author, title, publisherName; try { JSONObject obj = new JSONObject(response); //Results if (obj.getJSONObject("Results") != null) { JSONObject obj1 = obj.getJSONObject("Results"); //LookupTitleInfoResponse if (obj1.getJSONObject("LookupTitleInfoResponse") != null) { JSONObject obj2 = obj1.getJSONObject("LookupTitleInfoResponse"); //TitleInfo if (obj2.getJSONArray("TitleInfo") != null) { mArray = obj2.getJSONArray("TitleInfo"); JSONObject callInfo = mArray.getJSONObject(0); Log.i("callinfo", callInfo + ""); mArray2 = callInfo.getJSONArray("ItemInfo"); for (int i = 0; i <= mArray2.length(); i++) { if (mArray2.getJSONObject(i).getString("chargeable").equals("False")) { totalCount++; } if (mArray2.getJSONObject(i).getString("itemID").equals(scannedBarcode)) { avail = 1; } } author = mArray.getJSONObject(0).getString("author"); publisherName = mArray.getJSONObject(0).getString("publisherName"); title = mArray.getJSONObject(0).getString("title"); TitleTxt.setText(title); PublisherTxt.setText(publisherName); CreatorTxt.setText(author); BookBarcode.setText(scannedBarcode); AvailabiltyTxt.setText(totalCount); } } } } catch (JSONException e) { e.printStackTrace(); } } Getting error on below line: mArray2 = callInfo.getJSONArray("ItemInfo"); Error: org.json.JSONException: No value for ItemInfo 03-28 16:33:09.953 17229-17229/com.androidatc.customviewindrawer W/System.err: at org.json.JSONObject.get(JSONObject.java:389) 03-28 16:33:09.953 17229-17229/com.androidatc.customviewindrawer W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:584) Here we can clearly see that ItemInfo got value. Can anyone tell me - how to resolve above error? Many thanks in advance.
Try with below code mArray = obj2.getJSONArray("TitleInfo"); JSONObject titleInfo = mArray.getJSONObject(0); JSONArray arr1 = titleInfo.getJSONArray("CallInfo"); JSONObject callInfo = arr1.getJSONObject(0); JSONArray arr2 = callInfo.getJSONArray("ItemInfo"); Log.i("ItemInfo", arr2 + ""); Here is full method public void readBarCode(String response, String scannedBarcode) { final CountDownLatch latch = new CountDownLatch(1); final String[] names = new String[4]; JSONArray mArray, mArray1, mArray2; int totalCount = 0; int avail = 0; String author, title, publisherName; try { JSONObject obj = new JSONObject(response); //Results if (obj.getJSONObject("Results") != null) { JSONObject obj1 = obj.getJSONObject("Results"); //LookupTitleInfoResponse if (obj1.getJSONObject("LookupTitleInfoResponse") != null) { JSONObject obj2 = obj1.getJSONObject("LookupTitleInfoResponse"); //TitleInfo if (obj2.getJSONArray("TitleInfo") != null) { mArray = obj2.getJSONArray("TitleInfo"); JSONObject titleInfo = mArray.getJSONObject(0); JSONArray arr1 = titleInfo.getJSONArray("CallInfo"); JSONObject callInfo = arr1.getJSONObject(0); JSONArray arr2 = callInfo.getJSONArray("ItemInfo"); Log.i("ItemInfo", arr2 + ""); for (int i = 0; i < arr2.length(); i++) { if (arr2.getJSONObject(i).getString("chargeable").equals("False")) { totalCount++; } if (arr2.getJSONObject(i).getString("itemID").equals(scannedBarcode)) { avail = 1; } } author = mArray.getJSONObject(0).getString("author"); publisherName = mArray.getJSONObject(0).getString("publisherName"); title = mArray.getJSONObject(0).getString("title"); } } } } catch (JSONException e) { e.printStackTrace(); } }
Android: JSON Custom Merge
I have created two JSON like following, First Array: [ { "id":255, "is_new":0, "is_checked":true, "name":"Towel Rack 650", "is_favourite":false }, { "id":257, "is_new":0, "is_checked":true, "name":"Towel Rod 450", "is_favourite":false }, { "id":259, "is_new":0, "is_checked":true, "name":"Napkin Ring - Round", "is_favourite":false } ] Second Array: [ { "id":258, "is_new":0, "is_checked":false, "name":"Towel Rod 650", "is_favourite":true }, { "id":259, "is_new":0, "is_checked":false, "name":"Napkin Ring - Round", "is_favourite":true } ] In that I have to merge both array and also want to keep duplicate values once in final array. I used following snippet for merging. private JSONArray concatArray(JSONArray arr1, JSONArray arr2) throws JSONException { JSONArray result = new JSONArray(); for (int i = 0; i < arr1.length(); i++) { result.put(arr1.get(i)); } for (int i = 0; i < arr2.length(); i++) { result.put(arr2.get(i)); } return result; } I am getting: [ { "id":255, "is_new":0, "is_checked":true, "name":"Towel Rack 650", "is_favourite":false }, { "id":257, "is_new":0, "is_checked":true, "name":"Towel Rod 450", "is_favourite":false }, { "id":259, "is_new":0, "is_checked":true, "name":"Napkin Ring - Round", "is_favourite":false }, { "id":258, "is_new":0, "is_checked":false, "name":"Towel Rod 650", "is_favourite":true }, { "id":259, "is_new":0, "is_checked":false, "name":"Napkin Ring - Round", "is_favourite":true } ] In that I am getting duplicate values of id 259 which has different values of is_checked and is_favourite which I want true value for both like: { "id":259, "is_new":0, "is_checked":true, "name":"Napkin Ring - Round", "is_favourite":true } I have also tried SparseArray but not succeed. Is there any way to do this? Your help would be appreciated.
Alright, I wrote the code for you: First, preparing the objects: JSONArray arr1 = new JSONArray(),arr2 = new JSONArray(),result = new JSONArray(); JSONObject jobj = new JSONObject(); try { jobj.put("id", "255"); jobj.put("is_new", 0); jobj.put("is_checked", true); jobj.put("name", "Towel Rack 650"); jobj.put("is_favourite", false); arr1.put(jobj); jobj = new JSONObject(); jobj.put("id", "257"); jobj.put("is_new", 0); jobj.put("is_checked", true); jobj.put("name", "Towel Rod 450"); jobj.put("is_favourite", false); arr1.put(jobj); jobj = new JSONObject(); jobj.put("id", "259"); jobj.put("is_new", 0); jobj.put("is_checked", true); jobj.put("name", "Napkin Ring - Round"); jobj.put("is_favourite", false); arr1.put(jobj); jobj = new JSONObject(); jobj.put("id", "258"); jobj.put("is_new", 0); jobj.put("is_checked", false); jobj.put("name", "Towel Rod 650"); jobj.put("is_favourite", true); arr2.put(jobj); jobj = new JSONObject(); jobj.put("id", "259"); jobj.put("is_new", 0); jobj.put("is_checked", false); jobj.put("name", "Napkin Ring - Round"); jobj.put("is_favourite", true); arr2.put(jobj); result = concatArray(arr1, arr2); } catch (JSONException e) { e.printStackTrace(); } Then, the method: private JSONArray concatArray(JSONArray arr1, JSONArray arr2) throws JSONException { JSONArray result = new JSONArray(); JSONObject jobj1 = new JSONObject(),jobj2 = new JSONObject(),tmpobj = new JSONObject(); Set<String> objectsList = new HashSet<String>(); for (int i = 0; i < arr1.length(); i++) { if(objectsList.add(arr1.getJSONObject(i).getString("id"))){ result.put(arr1.getJSONObject(i)); } } for (int i = 0; i < arr2.length(); i++) { if(objectsList.add(arr2.getJSONObject(i).getString("id"))){ result.put(arr2.getJSONObject(i)); } else { jobj1 = arr2.getJSONObject(i); int index = 0; for(int j = 0; j < result.length(); j++){ if(result.getJSONObject(j).getString("id").equals(jobj1.getString("id"))){ jobj2 = result.getJSONObject(j); index = j; } } tmpobj.put("id", jobj2.getString("id")); tmpobj.put("is_new", jobj2.getInt("is_new")); if(jobj1.getBoolean("is_checked")||jobj2.getBoolean("is_checked")){ tmpobj.put("is_checked", true); } else { tmpobj.put("is_checked", false); } tmpobj.put("name", jobj2.getString("name")); if(jobj1.getBoolean("is_favourite")||jobj2.getBoolean("is_favourite")){ tmpobj.put("is_favourite", true); } else { tmpobj.put("is_favourite", false); } result.put(index, tmpobj); } } return result; }
You can add a SparseArray(key:id,value:each JSONObject in your JSONArray) to save your jsonobjects,every get a jsonobject,first check if its id has existed in SparseArray,if not,insert it.or you will do your logic to decide whether to insert it or update it or ignore it. At last,if you want to get a JSONArray as return type,then add all SparseArray's values to your JSONArray result.
how do i load swipe to refresh data at top listview android
Currently, my listview shows me current data. On Swipe, it will load old data from the server and store first old data and after current data. load server data at the top while swipe to refresh data. it is no updating data at the top level. Help me out for this situation. every time load data on top. and show loader while refreshing data while swipe to top to bottom. Thank you in advance. Here I am posting my code for review public class CommmentActivity extends Activity{ String Curl; boolean mBuzy; String UserId; String VidoId; String strComment; EditText etComment; String mPositionId = ""; String strfriendsSyncDate; ArrayAdapter<String> mentionList; ListCommentAdapter commentAdapter; AutoCompleteTextView aCompletView; DatabaseHandler db = new DatabaseHandler(this); List<CommentListInfo> list_CommentInfo = new ArrayList<CommentListInfo>(); ArrayList<MentionBeanClass> mList; MentionBeanClass addMention; List<String> SuggetionList; ImageView IvAddComment; ListView CommentList; SessionCreator m_session; boolean m = false; #Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.commentvideo_main); SuggetionList = new ArrayList<String>(); Curl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo"; Intent data = getIntent(); UserId = data.getStringExtra("userId"); VidoId = data.getStringExtra("videoId"); init(); strfriendsSyncDate = m_session.getfriendsSyncDate(); new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,mPositionId,Curl,"1"); ArratListBeans.setArMentionList(mList); commentAdapter = new ListCommentAdapter(getApplicationContext(), list_CommentInfo); CommentList.setAdapter(commentAdapter); CommentList.setOnScrollListener(new OnScrollListener() { #Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub switch (scrollState) { case OnScrollListener.SCROLL_STATE_IDLE:{ Log.d("ScrollStateCheck", ""+scrollState); break; } case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: { mBuzy = true; int count = CommentList.getCount(); if(CommentList.getFirstVisiblePosition()==0){ CommentListInfo c; c = (CommentListInfo) CommentList.getAdapter().getItem(CommentList.getFirstVisiblePosition()); mPositionId = c.CommentId; Log.d("mpositionId", mPositionId); String strUrl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo"; new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,c.CommentId,strUrl,"1"); } break; } case OnScrollListener.SCROLL_STATE_FLING:{ mBuzy = true; break; } default: break; } } #Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } }); IvAddComment.setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { // TODO Auto-generated method stub strComment = etComment.getText().toString(); etComment.getText().clear(); String strUrl = GlobalMethod.TokenGenerator() + "&action=addCommentsVideo"; new CommentsDetail().execute(UserId,VidoId,strComment,strUrl,"0"); new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,Curl,"1"); commentAdapter.notifyDataSetChanged(); } }); } private void init() { // TODO Auto-generated method stub m_session = new SessionCreator(getApplicationContext()); etComment = (EditText)findViewById(R.id.etComments); CommentList = (ListView)findViewById(R.id.lvLatestComments); IvAddComment = (ImageView)findViewById(R.id.addComment); mList = new ArrayList<MentionBeanClass>(); } public class CommentsDetail extends AsyncTask<String, String, String>{ #Override protected String doInBackground(String... params) { // TODO Auto-generated method stub ServiceHandler serviceClient; String mJsonString; try{ String userId = (String)params[0]; String vId = (String)params[1]; String syncdate = (String)params[2]; String startPosition = (String)params[3]; String strUrl = (String)params[4]; List<NameValuePair> paramsNameValuePairs = new ArrayList<NameValuePair>(); paramsNameValuePairs.add(new BasicNameValuePair("userId", userId)); paramsNameValuePairs.add(new BasicNameValuePair("videoId", vId)); paramsNameValuePairs.add(new BasicNameValuePair("startFrom", startPosition)); paramsNameValuePairs.add(new BasicNameValuePair("friendsSyncDate", syncdate)); serviceClient = new ServiceHandler(); mJsonString = serviceClient.makeServiceCall(strUrl, ServiceHandler.POST, paramsNameValuePairs); Log.i("---->>>>>>>>>>", paramsNameValuePairs + ""); Log.d("Response Json-----------------------",mJsonString ); return mJsonString; }catch (Exception e) { e.getStackTrace(); } return null; } #SuppressWarnings({ "unchecked", "unchecked", "unchecked" }) #Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); try{ if (result != null) { JSONObject responsJsonObj = new JSONObject(result); JSONObject jsonObj = (JSONObject) responsJsonObj .optJSONObject("data"); try { String str = jsonObj.getString("error"); if ( str != null || str.length() != 0) { // error //Toast.makeText(NewsfeedActivity.this, jsonObj.getString("error"),Toast.LENGTH_LONG).show(); return; } } catch (JSONException je) { Log.d("jex ------>", "" + je.getMessage()); try { String str = jsonObj.getString("message"); Log.d("message=", "" + str); if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("comments")) { JSONArray colArray = jsonObj.getJSONArray("comments"); Log.d("Colunm Array", ""+colArray); int nComments = colArray.length(); Log.d("# comments", "" + nComments); for(int i=0; i<nComments; i++){ JSONObject obj = colArray.getJSONObject(i); Gson Comments = new Gson(); String strComments = Comments.toJson(obj); Log.d("# obj=", "" + obj.toString()); CommentListInfo cmtInfo = new CommentListInfo(); cmtInfo.c_userId = obj.getString("userId"); cmtInfo.c_name = obj.getString("name"); cmtInfo.DateAdded = obj.getString("dateAdded"); cmtInfo.CommentId = obj.getString("commentId"); cmtInfo.CommentText = obj.getString("text"); cmtInfo.ImageUrl = obj.getString("imageLink"); list_CommentInfo.add(cmtInfo); } } } if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("addPosition")) { Log.d("# obj=", "" + jsonObj.toString()); Log.d("Add Position", jsonObj.getString("addPosition")); } } if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("mentions")) { JSONArray colArray = jsonObj.getJSONArray("mentions"); Log.d("Colunm Array", ""+colArray); int nMention = colArray.length(); Log.d("# mentions", "" + nMention); for(int i=0; i<nMention; i++){ JSONObject obj = colArray.getJSONObject(i); Log.d("# obj=", "" + obj.toString()); mList.add(new MentionBeanClass(obj.getString("id"), obj.getString("name"))); Log.d("Mention Info", "Id : "+obj.getString("id")+" Name : "+obj.getString("name")); } } } if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("videoUserData")) { Log.d("# obj=", "" + jsonObj.toString()); Log.d("videoUserData"," "+ jsonObj.getString("videoUserData")); } } if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("friendsAdded")) { JSONArray colArray = jsonObj.getJSONArray("friendsAdded"); String json = colArray.toString(); Log.d("Colunm Array", ""+colArray); int nfriendsAdded = colArray.length(); Log.d("# friendsAdded", "" + nfriendsAdded); for(int i=0; i<nfriendsAdded; i++){ JSONObject obj = colArray.getJSONObject(i); Log.d("# obj=", "" + obj.toString()); String id = obj.getString("userId"); String name = obj.getString("name"); String imgUrl = obj.getString("imageLink"); db.addCustomer(new FriendListInfo(id, name, imgUrl)); } } } if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("friendsDeleted")) { JSONArray colArray = jsonObj.getJSONArray("friendsDeleted"); Log.d("Colunm Array", ""+colArray); int nfriendsDeleted = colArray.length(); Log.d("# friendsDeleted", "" + nfriendsDeleted); for(int i=0; i<nfriendsDeleted; i++){ JSONObject obj = colArray.getJSONObject(i); Log.d("# obj=", "" + obj.toString()); } }else{ Log.d("Delete Friends", " No Deleted List"); } } if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("friendsUpdated")) { JSONArray colArray = jsonObj.getJSONArray("friendsUpdated"); Log.d("Colunm Array", ""+colArray); int nfriendsUpdated = colArray.length(); Log.d("# friendsDeleted", "" + nfriendsUpdated); for(int i=0; i<nfriendsUpdated; i++){ JSONObject obj = colArray.getJSONObject(i); Log.d("# obj=", "" + obj.toString()); } }else{ Log.d("Update Friends", " No Updated List"); } } if ( str != null || str.length() != 0) { // VALID RESPONSE, NOW PARSE IT if (jsonObj.has("friendsSyncDate")) { Log.d("# friendsDeleted", "" + jsonObj); Log.d("# obj=", "" + jsonObj.toString()); String myString = m_session.getfriendsSyncDate(); Log.d("myString", myString); m_session.putfriendsSyncDate(jsonObj.getString("friendsSyncDate")); Log.d("Sync Date "," "+jsonObj.getString("friendsSyncDate")); } } } catch (JSONException je2) { je2.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } } }
Add adapter-listview update code case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: { mBuzy = true; int count = CommentList.getCount(); if(CommentList.getFirstVisiblePosition()==0){ CommentListInfo c; c = (CommentListInfo) CommentList.getAdapter().getItem(CommentList.getFirstVisiblePosition()); mPositionId = c.CommentId; Log.d("mpositionId", mPositionId); String strUrl = GlobalMethod.TokenGenerator() + "&action=getCommentsVideo"; new CommentsDetail().execute(UserId,VidoId,strfriendsSyncDate,c.CommentId,strUrl,"1"); CommentList.setAdapter(commentAdapter); //update code }