onPostExecute() seems to be called only once - android

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.

Related

Can someone show me how I can pause my code until an onDataChange() Value event listener has completed?

Can someone please show me how I can pause my code in onCreate() until the event listener getting data from my firebase realtime DB has completed?
I have been stuck on this for a while now, anything that does not involve me completely reformatting my code would be awesome.
My code works but when getting data from the firebase my code continues to run without waiting for the EventListener to recieve the data...
I need to be able to stop the code but I do not know how...
-Just a suggestion: is it possible to use Thread.wait() and Thread.notify()?
I don't understand how threads/tasks/runnables work that well so a good explanation would be appreciated.
public void createNullRoom() {
room.setPlayerWhoIsSpyer(0);
room.add(1);
room.add(2);
room.add(3);
room.add(4);
room.add(5);
room.add(6);
room.setRoomCode("room_0");
room.setWinner(0);
room.setScene(0);
room.setRoundHasEnded(true);
room.setSecretWord("");
this.gameRoom.add(0,room);
pref.child(room.getRoomCode()).setValue(room);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "Game.onCreate");
setContentView(R.layout.gameview_public);
pId = 0;
room = new Room();
AssignUser = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
gameRoom.clear();
long v = snapshot.child("gameRoom").getChildrenCount();
int count = (int) v;
for (int i = 0; i < count + 1; i++) {
Room r = new Room();
boolean temp = true;
try {
r = snapshot.child("gameRoom").child("room_" + i).getValue(Room.class);
} catch (IndexOutOfBoundsException e) {
temp = false;
}
if (temp) {
gameRoom.add(r);
}
}
Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "gameRoom data retrieved");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
// ---- VALUE EVENT LISTENER TO GET DATA ------
AssignUser = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
gameRoom.clear();
long v = snapshot.child("gameRoom").getChildrenCount();
int count = (int) v;
for (int i = 0; i < count + 1; i++) {
Room r = new Room();
boolean temp = true;
try {
r = snapshot.child("gameRoom").child("room_" + i).getValue(Room.class);
} catch (IndexOutOfBoundsException e) {
temp = false;
}
if (temp) {
gameRoom.add(r);
Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "\tSize: " + gameRoom.size());
}
}
Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "gameRoom data retrieved");
Log.e(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "inside the snapshot, gamerooms.size: " + gameRoom.size() + " line 343");
assignUser();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
// ------------------------------------------------
ref.addListenerForSingleValueEvent(AssignUser);
createNullRoom();
// ===================================THIS NEEDS TO PAUSE HERE
int i = 0;
while(playerjoined == false) {
boolean exists = true;
Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "line 431: if");
try {
this.room = this.gameRoom.get(i);
} catch (IndexOutOfBoundsException e) {
exists = false;
}
if (exists) {
this.room = gameRoom.get(i);
this.roomcode = this.room.getRoomCode();
for (int q = 1; q < 7; q++) {
if(this.getFalse() == q) {
this.room.add(q);
this.pref.child(this.roomcode).setValue(this.room);
this.pId = q;
q = 6;
playerjoined = true;
}
}
if(playerjoined == false) {
i++;
}
} else {
CreateNewPublicRoom(i);
Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "Game.java/" + Thread.currentThread().getStackTrace()[1].getLineNumber() + "\tNew Public Room Made");
pref.child(this.roomcode).setValue(this.room);
Log.e(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(),"OUTSIDE the snapshot, gamerooms.size: " + gameRoom.size() + " line 403");
Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "\tThis.playerjoined == "+playerjoined);
}
}
ref.child("gameRoom").child(this.room.getRoomCode()).setValue(this.room)
etc...

Access to google calendar events

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

Get Cached data storage programmatically

I want to get cached data size at "Internal storage" in "settings", like this:
I tried to get all application cache by invoking getPackageSizeInfo using Java Reflection. Yes it did got all cached size of apps, but the size is smaller than the cached data size in "settings" above. This is the picture when I used this method:
in settings, the cached data size 840 MB, but when in my app is 493 MB.
These are my codes
Main Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int FETCH_PACKAGE_SIZE_COMPLETED = 100;
public static final int ALL_PACKAGE_SIZE_COMPLETED = 200;
IDataStatus onIDataStatus;
TextView lbl_cache_size;
ProgressDialog pd;
long packageSize = 0, size = 0, dataSize = 0, data = 0;
AppDetails cAppDetails;
public ArrayList<AppDetails.PackageInfoStruct> res;
int totalSize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_get_cacheSize).setOnClickListener(this);
findViewById(R.id.btn_delete_cache).setOnClickListener(this);
lbl_cache_size = (TextView) findViewById(R.id.lbl_cache_size);
}
private void showProgress(String message) {
pd = new ProgressDialog(this);
pd.setIcon(R.mipmap.ic_launcher);
pd.setTitle("Please wait...");
pd.setMessage(message);
pd.setCancelable(false);
pd.show();
}
private void getPackageSize() {
cAppDetails = new AppDetails(this);
res = cAppDetails.getPackages();
if (res == null)
return;
for (int m = 0; m < res.size(); m++) {
PackageManager pm = getPackageManager();
Method getPackageSizeInfo;
try {
getPackageSizeInfo = pm.getClass().getMethod(
"getPackageSizeInfo", String.class,
IPackageStatsObserver.class);
getPackageSizeInfo.invoke(pm, res.get(m).pname,
new cachePackState());
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
handle.sendEmptyMessage(ALL_PACKAGE_SIZE_COMPLETED);
Log.v("Total Cache Size", " " + packageSize);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_get_cacheSize:
size = 0;
packageSize = 0;
dataSize = 0;
data = 0;
showProgress("Calculating Cache Size..!!!");
/*
* You can also use sync task
*/
new Thread(new Runnable() {
#Override
public void run() {
getPackageSize();
}
}).start();
//getPackageSize();
break;
case R.id.btn_delete_cache:
deleteCache();
break;
default:
break;
}
}
private Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FETCH_PACKAGE_SIZE_COMPLETED:
String sizeInHuman = "";
if (packageSize > 0) {
// size = (packageSize / 1024000);
//data = (dataSize / 1024000); //boy
sizeInHuman = humanReadableByteCount(packageSize, true);
}
//lbl_cache_size.setText("Cache Size : " + size + " MB and Data Size : "+ data + " MB");
lbl_cache_size.setText("Cache Size : " + sizeInHuman);
break;
case ALL_PACKAGE_SIZE_COMPLETED:
if (null != pd)
if (pd.isShowing())
pd.dismiss();
break;
default:
break;
}
}
};
private class cachePackState extends IPackageStatsObserver.Stub {
#Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
Log.d("Package Size", pStats.packageName + "");
Log.i("Cache Size", pStats.cacheSize + "");
Log.w("Data Size", pStats.dataSize + "");
packageSize = packageSize + pStats.cacheSize;
Log.v("Total Cache Size", " " + packageSize );
handle.sendEmptyMessage(FETCH_PACKAGE_SIZE_COMPLETED);
}
}
private void deleteCache() {
PackageManager pm = getPackageManager();
//Get all methods on the packageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
//Found the method I want to use
try {
m.invoke(pm, Long.MAX_VALUE, null);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
AppDetails
public class AppDetails {
Activity mActivity;
public ArrayList<PackageInfoStruct> res = new ArrayList<PackageInfoStruct>();
public ListView list;
public String app_labels[];
public AppDetails(Activity mActivity) {
this.mActivity = mActivity;
}
public ArrayList<PackageInfoStruct> getPackages() {
ArrayList<PackageInfoStruct> apps = getInstalledApps(true); /*
* false =
* no system
* packages
*/
final int max = apps.size();
for (int i = 0; i < max; i++) {
apps.get(i);
}
return apps;
}
private ArrayList<PackageInfoStruct> getInstalledApps(boolean getSysPackages) {
List<PackageInfo> packs = mActivity.getPackageManager()
.getInstalledPackages(0);
try {
app_labels = new String[packs.size()];
} catch (Exception e) {
Toast.makeText(mActivity.getApplicationContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
//if ((!getSysPackages) && (p.versionName == null)) {
// continue;
//}
PackageInfoStruct newInfo = new PackageInfoStruct();
newInfo.appname = p.applicationInfo.loadLabel(
mActivity.getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.datadir = p.applicationInfo.dataDir;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(mActivity
.getPackageManager());
res.add(newInfo);
app_labels[i] = newInfo.appname;
}
return res;
}
class PackageInfoStruct {
String appname = "";
String pname = "";
String versionName = "";
int versionCode = 0;
Drawable icon;
String datadir = "";
}
}
Is there any way to get cached data size in storage?
The reference:
reference

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

Android SYNCHRONIZATION with SQL mgmt studio using JSON

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

Categories

Resources