I want to get the events from a public google calendar in my app.
This is my activity, with the access to somePublicCalendar#google.com which I've changed for a fake account, but my calendar is public. Of course, somePublicCalendar#gmail.com is not my account and I can't manage it. Just want to see if I there's a gap for scheduling and appointment.
This is my activity, and for the moment, the cursor seems to be empty.
public class calendar extends AppCompatActivity implements View.OnClickListener{
CalendarView calendarView;
final int callbackId = 42;
Button home;
// Projection array. Creating indices for this array instead of doing
// dynamic lookups improves performance.
public static final String[] EVENT_PROJECTION = new String[] {
CalendarContract.Calendars._ID, // 0
CalendarContract.Calendars.ACCOUNT_NAME, // 1
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, // 2
CalendarContract.Calendars.OWNER_ACCOUNT // 3
};
// The indices for the projection array above.
private static final int PROJECTION_ID_INDEX = 0;
private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
home = findViewById(R.id.inicio);
calendarView = findViewById(R.id.calendarView);
checkPermission(callbackId, Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
consultarCalendario();
}
});
}
#Override
public void onRequestPermissionsResult(int callbackId,
String permissions[], int[] grantResults) {
}
public void consultarCalendario() {
// Run query
Cursor cur = null;
ContentResolver cr = getContentResolver();
Uri uri = CalendarContract.Calendars.CONTENT_URI;
String selection = "((" + CalendarContract.Calendars.ACCOUNT_NAME + " = ?) AND ("
+ CalendarContract.Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ CalendarContract.Calendars.OWNER_ACCOUNT + " = ?))";
String[] selectionArgs = new String[]{"somePublicCalendar#gmail.com", "com.google",
"somePublicCalendar#gmail.com"};
// Submit the query and get a Cursor object back.
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
// Use the cursor to step through the returned records
while (cur.moveToNext()) {
long calID = 0;
String displayName = null;
String accountName = null;
String ownerName = null;
// Get the field values
calID = cur.getLong(PROJECTION_ID_INDEX);
displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
// Do something with the values...
Log.d("Conexion a calendario",calID + "/" + displayName+ "/" + accountName + "/" + ownerName);
}
}
private void checkPermission(int callbackId, String... permissionsId) {
boolean permissions = true;
for (String p : permissionsId) {
permissions = permissions && ContextCompat.checkSelfPermission(this, p) == PERMISSION_GRANTED;
}
if (!permissions)
ActivityCompat.requestPermissions(this, permissionsId, callbackId);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.inicio:
startActivity(new Intent(this, Principal.class));
break;
}
}
}
I'm not familiar with the Calendar libraries you are using, but this is how I got entries from a Google Calendar:
private void callGetEvents() {
String sURL1 = "https://www.googleapis.com/calendar/v3/calendars/somePublicCalendar%40gmail.com/events?key=XYZTHECALENDARKEYZYX";
getEvents(sURL1);
}
private void getEvents(String url) {
final ProgressDialog dialog;
dialog = new ProgressDialog(thisContext);
dialog.setMessage((String) getResources().getText(R.string.loading_please_wait));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
listOfEvents = new ArrayList<EventItem>();
JsonObjectRequest req = new JsonObjectRequest(url, null, new Response.Listener<JSONObject> () {
#SuppressLint("SimpleDateFormat")
#Override
public void onResponse(JSONObject response) {
try {
JSONArray items = response.getJSONArray("items");
Date today = new Date();
for (int i = 0; i < items.length(); i++) {
JSONObject oneObject = null;
try {
oneObject = items.getJSONObject(i);
} catch (JSONException e) {
continue;
}
String title = "";
try {
title = oneObject.getString("summary");
} catch (JSONException e) {
title = "";
}
String description = "";
try {
description = oneObject.getString("description");
} catch (JSONException e) {
description = "";
}
String location = "";
try {
location = oneObject.getString("location");
} catch (JSONException e) {
location = "";
}
JSONObject startObject = null;
String startDate = "";
Date start_date = new Date();
JSONObject endObject = null;
String endDate = "";
Date end_date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
startObject = oneObject.getJSONObject("start");
startDate = startObject.getString("dateTime");
try {
start_date = dateFormat.parse(startDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
endObject = oneObject.getJSONObject("end");
endDate = endObject.getString("dateTime");
try {
end_date = dateFormat.parse(endDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
EventItem item = new EventItem(title, description, location, start_date, end_date);
Log.i("Compare", today.toString() + ":" + endDate);
if (title.length() > 0) {
if (today.compareTo(end_date) < 0) {
listOfEvents.add(item);
}
}
}
Collections.sort(listOfEvents, new Comparator<EventItem>() {
public int compare(EventItem o1, EventItem o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
});
try {
adapter = new EventListAdapter(thisContext, listOfEvents);
eventListView.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
dialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
Log.e("Error: ", error.getMessage());
dialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json; charset=UTF-8");
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
};
};
// add the request object to the queue to be executed
MyApplication.getInstance().addToRequestQueue(req);
}
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()
}
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;
}
}