Android Volley inside for loop For showing progress - android

I need to show a loading screen for volley, I am sending few json to the servers using volley, i written the code inside for loop for fetching a json and sending the json. But the for loop is not waiting for the responce to continue. It just completing quickly, How can i use for loop for sending jason and show the for loops value as the count of syncing.?
Code...
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
Log.d("length", String.valueOf(result.length()));
if(result.length()!=0) {
for (int e = 0; e < result.length(); e++) {
this.dialog.setMessage("Syncing "+(e+1)+" of "+result.length());
this.dialog.show();
try {
final JSONObject js = result.getJSONObject(e);
Log.d("sdfhd", js.toString());
final JSONArray ja = new JSONArray();
ja.put(js);
Log.d("sending json", ja.toString());
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
server_url, ja,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("asd", ja.toString());
Log.d("JsonArray", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject store = response.getJSONObject(i);
mydb.updateweb(store.getInt("_id"), store.getString("webid"), store.getString("regid"));
if (i == response.length() - 1) {
Toast.makeText(MainActivity.this, "Synced Successfully", Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
JSONObject stor = response.getJSONObject(0);
Toast.makeText(MainActivity.this, stor.getString("result"),
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
// dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Json sdfsdfsf", js.toString());
Log.d("afs", error.toString());
Toast.makeText(MainActivity.this, "error",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
else{
Toast.makeText(MainActivity.this, "Updated Succesfully",
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
// dialog.dismiss();
}

Look at the code I have changed your logic about the dialog, also I have added success and failure counts functionality so that you can have an idea of request statuses
Global Variables:
int successCount = 0;
int failedCount = 0;
Revised onPostExecute():
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
successCount = 0;
failedCount = 0;
this.dialog.setMessage("Syncing 0 of "+result.length());
this.dialog.show();
Log.d("length", String.valueOf(result.length()));
if(result.length()!=0) {
for (int e = 0; e < result.length(); e++) {
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
try {
final JSONObject js = result.getJSONObject(e);
Log.d("sdfhd", js.toString());
final JSONArray ja = new JSONArray();
ja.put(js);
Log.d("sending json", ja.toString());
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
server_url, ja,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
boolean isCodeExecutedSuccessfully = false;
Log.d("asd", ja.toString());
Log.d("JsonArray", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject store = response.getJSONObject(i);
mydb.updateweb(store.getInt("_id"), store.getString("webid"), store.getString("regid"));
if (i == response.length() - 1) {
Toast.makeText(MainActivity.this, "Synced Successfully", Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
isCodeExecutedSuccessfully = true;
} catch (JSONException e) {
isCodeExecutedSuccessfully = false;
e.printStackTrace();
}
}
try {
JSONObject stor = response.getJSONObject(0);
Toast.makeText(MainActivity.this, stor.getString("result"),
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
// dialog.dismiss();
isCodeExecutedSuccessfully = true;
} catch (JSONException e) {
isCodeExecutedSuccessfully = false;
e.printStackTrace();
}
//////////////////////////////// DIALOG WORK ON SUCCESS ///////////////////////////////
if(isCodeExecutedSuccessfully)
++successCount;
else
++failedCount;
if((e+1) == result.length()) {
dialog.dismiss();
}
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
Log.d("::onResponse(): Status Counts", "Success=" + successCount + ", fail=" + failedCount);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//////////////////////////////// DIALOG WORK ON ERROR RESPONSE ///////////////////////////////
++failedCount;
if((e+1) == result.length()) {
dialog.dismiss();
}
Log.d("::onErrorResponse(): Status Counts", "Success=" + successCount + ", fail=" + failedCount);
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
Log.d("Json sdfsdfsf", js.toString());
Log.d("afs", error.toString());
Toast.makeText(MainActivity.this, "error",
Toast.LENGTH_SHORT).show();
//dialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
else{
Toast.makeText(MainActivity.this, "Updated Succesfully",
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
// dialog.dismiss();
}

Related

BasicNetwork.performRequest: Unexpected response code 400,marker doesnt show up

problem : after click on search the marker doesn't show up again and give me error response code 400 for ( link )
logcat error
E/Response:: [{"lat":"-7.552991","lng":"110.798546","id":"13","nama":"SMK 4 NEGERI SURAKARTA"}]
E/Volley: [4208] BasicNetwork.performRequest: Unexpected response code 400 for http://tugasupload.esy.es/api/maps.php?latitude=SMK 4 NEGERI SURAKARTA
and source code
private void getMarkers() {
System.out.println("abc");
dialog.setMessage("Mengambil Data");
dialog.setCancelable(false);
dialog.show();
JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.GET,
"http://tugasupload.esy.es/api/maps.php?latitude=" + ambilcari, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject data = response.getJSONObject(i);
title = data.getString("nama");
id = data.getInt("id");
latLng = new LatLng(Double.parseDouble(data.getString(LAT)), Double.parseDouble(data.getString(LNG)));
lokasi = data.getString("nama");
// Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title, lokasi, id);
} catch (JSONException e) {
e.printStackTrace();
}
}
dialog.cancel();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.cancel();
Toast.makeText(getApplication(), "Ada Kesalahan Mohon Periksa Kembali", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(reqData);
}
#Override
public void onClick(View view) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
ambilcari = acTextView.getText().toString();
lokasi();
gMap.clear();
}
private void lokasi() {
dialog.setMessage("Loading...");
dialog.show();
String url1 = "http://tugasupload.esy.es/api/lokasi.php?latitude=" + ambilcari;
url1= url1.replaceAll(" ", "%20");
System.out.println(url1);
StringRequest strReq = new StringRequest(Request.Method.GET, url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response);
try {
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
System.out.println(latLng);
lati = Double.parseDouble(jsonObject.getString(LAT));
longi = Double.parseDouble(jsonObject.getString(LNG));
if (ambilcari.equals(" ")) {
center = new LatLng(-7.568737, 110.827062);
cameraPosition = new CameraPosition.Builder().target(center).zoom(10).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
getMarkers();
} else {
center = new LatLng(lati, longi);
cameraPosition = new CameraPosition.Builder().target(center).zoom(12).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
getMarkers();
}
}
dialog.dismiss();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse( VolleyError volleyError ) {
try {
String responseBody = new String( volleyError.networkResponse.data, "utf-8" );
JSONObject jsonObject = new JSONObject( responseBody );
} catch ( JSONException e ) {
//Handle a malformed json response
} catch (UnsupportedEncodingException ignored){
}
}
}
);
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
and i am trying to solve this case by following :
Android Volley - BasicNetwork.performRequest: Unexpected response code 400
and adding url = url.replaceAll(" ", "%20"); before adding this code after search, force close app

Handle response of multiple request from Volley Library

I am sending multiple request through for loop.
On response I get success or failure message, and I need to show this message in a AlertDialog.
My Problem is: when I am sending 10 request then I am getting 10 response hence 10 times dialogue is showing with response.
I want to show only one dialogue when all response will have come,and that dialogue should contain response according to their each and every request.
How can I do it.
code which I tried:
if (globalInstance.isNetworkAvailable(AddBookingList.this)) {
int si = checkedItems.size();
if (checkedItems.size() > 0) {
for (int i = 0; i < si; i++) {
int appid = checkedItems.get(i).getAppid();
int bookingId = checkedItems.get(i).getBookingid();
List<Contacts> con = db.getadvertisment(bookingId);
List<AddImages> img = db.getImagesbybookingId(bookingId);
String postXml = createxmlForPost(con, img);
sendDataToServer(postXml,appid, bookingId, si);
}
}
}
private void sendDataToServer(final String postXml, final int appid, final int bookingId, final int si) {
final ProgressDialog progressDialog = new ProgressDialog(this, R.style.AppCompatAlertDialogStyle);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
try {
final RequestQueue queue = Volley.newRequestQueue(this);
JSONObject obj = new JSONObject();
obj.put("xmlData", postXml);
int socketTimeout = 30000;//30 seconds
final StringRequest postRequest = new StringRequest(Request.Method.POST, Constants.Rootpath + "PostBooking",
new Response.Listener<String>() {
#Override
public void onResponse(String st) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
JSONArray response = new JSONArray(st);
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
int status = jsonObject.getInt("Status");
String msg = jsonObject.getString("Msg");
String serverbooking_id = jsonObject.getString("BookingId");
if (status == 1) {
checkedItems.clear();
if (response.length() > 1) {
String newserverbooking_id = response.getJSONObject(0).getString("BookingId") + "\n" + response.getJSONObject(1).getString("BookingId");
db.updateBookingDetailsbyAppId(newserverbooking_id, appid, status);
} else {
db.updateBookingDetailsbyAppId(serverbooking_id, appid, status);
}
showDatainList();
globalInstance.showSuceessMessage(true, "Success!!! Your BookingID is: " + serverbooking_id, AddBookingList.this);
try {
List<Contacts> contacts = db.getAllBookingDetails();
for (int h = 0; h < contacts.size(); h++) {
locallySaveImagesinPhone(bookingId, contacts.get(h).get_serverbookingId());
}
} catch (IOException e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
globalInstance.showFailureMessage(false, "Booking Failed." + msg, AddBookingList.this);
checkedItems.clear();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
String msg = error.getMessage();
globalInstance.showFailureMessage(false, "Booking Failed.Please Try Again!!!", AddBookingList.this);
}
}
) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>();
params.put("xmldata", postXml);
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
queue.add(postRequest);
} catch (JSONException e1) {
e1.printStackTrace();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
As i understand your problem is calling globalInstance.showSuceessMessage() or globalInstance.showFailureMessage every time you get the response.
what i think might work is:
Instead of these two methods, define an Arraylist<String> and based on the
success or failure of the response add messages to it like "Success!!! Your BookingID is: " + serverbooking_id and "Booking Failed." + msg.
Define a method like showMessages() which has a dialogue containing the messages u added to arraylist before. then call it after where you called thesendDataToServer method which is in the if (checkedItems.size() > 0) block.

fetch Bunch of data from server to Local Db While Opening the android app, without Affecting UI thread(App is not Responding Error)

i am fetching Bunch of data from server to Local Database ,after Login.
its getting some times Alert App is not Responding Wait or Close.
Please help me any other Possible way or try to fix this issue.
Async call:
Asynctask_GetServerData task=new Asynctask_GetServerData ();
task.execute();
Asynctask Class:
public class Asynctask_GetServerData extends AsyncTask<String,Void,Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
if (!pDialog.isShowing())
{
pDialog.setIndeterminate(true);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setMessage("Please Wait Getting Data...");
pDialog.show();
}
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(String... params)
{
getLoginDataCall();
return null;
}
}
private void getLoginDataCall() {
sisClient.getApi().getAllData(
new Callback<CommonResponse>() {
#Override
public void success(CommonResponse commonResponse, Response response) {
Timber.d("sendOtpAPICall%s", commonResponse.getStatusCode());
switch (commonResponse.getStatusCode()) {
case 200:
try {
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(commonResponse.getRouteMaster());
if (!commonResponse.getRouteMaster().equals("[]"))
{
for (int i = 0; i < jsonarray.length(); i++)
{
JSONObject jsonobject = jsonarray.getJSONObject(i);
RouteId_StringValue = jsonobject.getString("RouteId");
Asynxfor_Route_Master_insert(RouteId_StringValue);
}
} else {
System.out.println("ROute Master Is NULL ::" + commonResponse.getStatusMessage() + "\n");
}
} catch (Exception e) {
e.printStackTrace();
;
}
break;
case 404:
pDialog.dismiss();
Toast.makeText(LoginPage.this, R.string.wrong_Username_or_password, Toast.LENGTH_LONG).show();
break;
case 500:
pDialog.dismiss();
Toast.makeText(LoginPage.this, R.string.something_wrong, Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void failure(RetrofitError error) {
try {
if (error != null) {
pDialog.dismiss();
Timber.i("sendOtpAPICall error %s", error.getResponse().getStatus());
String json = new String(((TypedByteArray) error.getResponse().getBody()).getBytes());
Timber.i("failure error %s", json.toString());
JSONObject json1 = new JSONObject(json.toString());
String json1string = json1.getString("StatusMessage");
switch (error.getResponse().getStatus()) {
case 404:
Toast.makeText(getApplicationContext(), R.string.wrong_Username_or_password, Toast.LENGTH_LONG).show();
break;
case 500:
Toast.makeText(LoginPage.this, R.string.something_wrong, Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(LoginPage.this, json1string, Toast.LENGTH_LONG).show();
break;
}
} else {
Timber.i("failure error %s", "Recieving error null rom server");
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(LoginPage.this, R.string.something_wrong, Toast.LENGTH_LONG).show();
}
}
});
}

ParseError: org.json.JSONException:

I'm getting the following error:
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
This is my code:
public void onResponse(JSONObject response) {
dialog.dismiss();
Log.d("response", response.toString());
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("assignments");
if(jsonArray.length()==0)
{
Toast.makeText(getApplicationContext(), "Assignments Not Found", Toast.LENGTH_LONG).show();
}
CardView cardView=(CardView)findViewById(R.id.list_item5);
cardView.setVisibility(View.VISIBLE);
assignmentModuleListList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
AssignmentModule assignmentModule = new AssignmentModule();
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
assignmentModule.setAssignmentName(jsonObject1.getString("assignmentName"));
assignmentModule.setDescription(jsonObject1.getString("description"));
assignmentModule.setSubjectName(jsonObject1.getString("subjectName"));
String date=jsonObject1.getString("startDate").substring(0,10);
String date1=jsonObject1.getString("endDate").substring(0, 10);
assignmentModule.setAssignDate(date+"\n"+"\t\t\t"+"to"+"\n"+date1);
assignmentModuleListList.add(assignmentModule);
}
setdata(assignmentModuleListList);
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Log.d("error",error.toString());
String timeout=error.toString();
if(timeout.equalsIgnoreCase("com.android.volley.TimeoutError"))
{
Toast.makeText(getApplicationContext(), "Opp's Server Can't Load Please Try Again Latter", Toast.LENGTH_LONG).show();
}
NetworkResponse response = error.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode){
case 400:
Toast.makeText(getApplicationContext(), "400 Error", Toast.LENGTH_LONG).show();
break;
case 404:
Toast.makeText(getApplicationContext(), "Assignments Not Found", Toast.LENGTH_LONG).show();
break;
case 500:
Toast toast1 = Toast.makeText(getApplicationContext(), "Internal Server Error", Toast.LENGTH_SHORT);
TextView v1 = (TextView) toast1.getView().findViewById(android.R.id.message);
v1.setTextColor(Color.RED);
toast1.show();
break;
}
//Additional cases
}
}
This is what I'm expecting after parsing:
{
"assignments":[
{
"assignmentName":"asignment1",
"description":"first poam",
"subjectName":"kannada",
"startDate":"2016-01-22",
"endDate":"2016-01-23"
},
{
"assignmentName":"assigment3",
"description":"thrid lesson",
"subjectName":"kannada",
"startDate":"2016-01-22",
"endDate":"2016-01-23"
}
]
}

How to get friends info that requires permission like B'day using facebook graph api

I'm having android Button for Login.
below is the onclick listener of that button.
btnLoginFB.setOnClickListener(new View.OnClickListener() {
#
Override
public void onClick(View v) {
Session s = new Session(Startup.this);
Session.setActiveSession(s);
Session.OpenRequest request = new Session.OpenRequest(Startup.this);
List < String > permissions = new ArrayList < String > ();
permissions.add("friends_birthday");
permissions.add("friends_location");
request.setPermissions(permissions);
request.setCallback(new Session.StatusCallback() {
#
Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.newMyFriendsRequest(Session.getActiveSession(), new Request.GraphUserListCallback() {
#
Override
public void onCompleted(List < GraphUser > users, Response response) {
if (users != null) {
for (int i = 0; i < users.size(); i++) {
String frndLoc = "empty";
try {
users.get(i).getLocation().getProperty("name");
frndLoc = "" + users.get(i).getLocation().getProperty("name");
} catch (Exception e) {}
Toast.makeText(Startup.this, users.get(i).getBirthday() + " - " +
users.get(i).getName() + "\n" +
frndLoc, Toast.LENGTH_LONG).show();
}
}
}
}).executeAsync();
} // end of if (session.isOpened())
} // end of call
});
s.openForRead(request);
}
});
The problem is I'm getting null for both B'day and Location of friend.
Request friendRequest = Request.newMyFriendsRequest(activeSession, new GraphUserListCallback() {
#Override
public void onCompleted(final List<GraphUser> users, Response response) {
ArrayList<String> o = new ArrayList<String>();
for (GraphUser u : users) {
o.add(u.getInnerJSONObject().toString());
}
getSherlockActivity().startService(
new Intent(getSherlockActivity(), InsertInDBService.class).putExtra("fbdata", o));
}
}
});
Parse the reponse
int count = users.size();
for (int i = 0; i < count; i++) {
String name = "", id = "", photoUrl = "";
String birthday = "", location = "";
String website = "";
JSONObject o = null;
try {
o = new JSONObject(users.get(i));
} catch (JSONException e) {
}
try {
id = o.getString("id");
name = o.getString("name");
photoUrl = o.getJSONObject("picture").getJSONObject("data").getString("url");
} catch (JSONException e) {
e.printStackTrace();
dbFacebookMain.deleteFACEBOOK();
}
try {
location = o.getJSONObject("location").getString("name");
} catch (JSONException e) {
}
try {
birthday = o.getString("birthday");
} catch (JSONException e) {
}
try {
website = o.getString("website");
} catch (JSONException e) {
}

Categories

Resources