Json takes multiple attempts to get downloaded correctly - android

I am asking the same question I asked previously as I'm unable to solve the issue. You can follow the link: https://stackoverflow.com/questions/40017707/unable-to-get-correct-json
Don't be judgemental before trying it manually at your end.I'd like to know where am I mistaking here.
Thanks
Older Post:-
I've 1 url: http://alolma.coderswebsites.com/api/v1/person/ and I tried following diff libs but unable to parse the correct json.
It shows org.json.JSONException: Unterminated string at character 21001 while using okhttp.
� while using volley (with parseNetworkResponse also).
com.loopj.android:android-async-http:1.4.9- it aprses the json but here, new issues arises that the size of the result array varies (I don't know how) & I use the count jsonobj to match the size of it but it takes 5-8 hits to get the correct json data.
Plz help me and let me know wh this happening, the data is in UT-8 already,so I did not decode it.
Volley coding:-
public void getPersonList(Context context) {
UTF8StringRequest stringRequest = new UTF8StringRequest (com.android.volley.Request.Method.GET,"http://alolma.coderswebsites.com/api/v1/person/",
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response",response);
try{
list.clear();
JSONObject obj = new JSONObject(response);
count=obj.getInt("count");
Log.d("count",""+count);
Log.d("lenofresult",""+obj.getJSONArray("results").length());
for (int i=0; i<obj.getJSONArray("results").length(); i++) {
Person person = new Person();
person.parse(obj.getJSONArray("results").getJSONObject(i));
list.add(person);
}
Log.d("list.siz()",""+list.size());
if (list.size()==count)
{ Log.d("data","100%");
loadagain=false;
list2=list;
callBack.onSuccess();
}
}
catch (Exception e){}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
For this I use -
public class UTF8StringRequest extends StringRequest {
public UTF8StringRequest(int method, String url, com.android.volley.Response.Listener listener, com.android.volley.Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
public UTF8StringRequest(String url, com.android.volley.Response.Listener<String> listener, com.android.volley.Response.ErrorListener errorListener) {
super(url, listener, errorListener);
}
#Override
protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) {
String utf8String = null;
try {
utf8String = new String(response.data, "UTF-8");
return com.android.volley.Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return com.android.volley.Response.error(new ParseError(e));
}
}
}
try asynctask-
class getdata extends AsyncTask {
#Override
protected void onPreExecute() {
loadagain=false;
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
Log.d("inside","getunseenmsg");
String s="";
URL url = null;
try {
url = new URL("http://alolma.coderswebsites.com/api/v1/person/");
final InputStream inputStream = url.openStream();
final InputStreamReader inputStreamReader
= new InputStreamReader(inputStream, "UTF-8");
StringBuffer stringBuffer = new StringBuffer();
char[] buffer = new char[2000];
while (inputStreamReader.read(buffer, 0, 2000) != -1) {
stringBuffer.append(buffer);
}
Log.d("RAW_STRING", stringBuffer.toString());
list.clear();
JSONObject obj = new JSONObject(stringBuffer.toString());
inputStreamReader.close();
count=obj.getInt("count");
Log.d("count",""+count);
Log.d("lenofresult",""+obj.getJSONArray("results").length());
for (int i=0; i<obj.getJSONArray("results").length(); i++) {
Person person = new Person();
person.parse(obj.getJSONArray("results").getJSONObject(i));
list.add(person);
}
Log.d("list.siz()",""+list.size());
if (list.size()==count)
{ Log.d("data","100%");
loadagain=false;
list2=list;
callBack.onSuccess();
}
else
{ loadagain=true;
getPersonList();}
} catch (Exception e) {
e.printStackTrace();
Log.d("list.siz()",""+list.size());
list.clear();
if (list.size()==count & count>0)
{Log.d("data","100%");
loadagain=false;
list2.addAll(list);
callBack.onSuccess();
}
else
{ loadagain=true;
getPersonList();}
}
return s;
// TODO Auto-generated method stub
}
protected void onPostExecute(String params) {
super.onPostExecute(params);
}
}

Related

Volley POST request Android token

I am new to new android programming and currently working with the Volley POST request library for a login page. I already have a working API which gives a String token when you make a post request. For now I have hard coded the username and password just to see if the post request works by creating a Toast. However, when I click on the submit button it prints out 200 in toast which doesnt make sense because the token is very big. It takes a few seconds for the toast to appear. This is what the API gives(I need the token):
{
"status": true,
"result": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjI4OTkiLCJvdGhlciI6eyJ1c2VyX2lkIjoiMjg5OSIsImRvbWFpbl9saXN0X2ZrIjoiMSIsInV1aWQiOiIxNTY4NzA2Mjg4ODk5IiwidXNlcl90eXBlIjoiNCIsInJlZ190eXBlIjoiMSIsImVtYWlsIjoiZmFpc2FsY2t5ZkBnbWFpbC5jb20iLCJwYXNzd29yZCI6ImY0NjY4Mjg4ZmRiZjk3NzNkZDk3NzlkNDEyOTQyOTA1Iiwic3RhdHVzIjoiMSIsImRhdGVfb2ZfYmlydGgiOm51bGwsImltYWdlIjpudWxsLCJ0aXRsZSI6bnVsbCwiYWdlbmN5X25hbWUiOm51bGwsImFnZW50X25hbWUiOm51bGwsImFnZW5jeV9lbWFpbCI6IiIsImZpcnN0X25hbWUiOiJGYWlzYWwiLCJtaWRkbGVfbmFtZSI6IiIsImxhc3RfbmFtZSI6bnVsbCwiYWRkcmVzcyI6IjMxIEQiLCJjaXR5IjoiUmFzaGlkaXlhIiwic3RhdGUiOiJEdWJhaSIsImNvdW50cnlfY29kZSI6IjIxMiIsImNvdW50cnlfbmFtZSI6IlVuaXRlZCBBcmFiIEVtaXJhdGVzIiwicGhvbmUiOiIwNTY2OTkzNzA5IiwicGhvbmVfY29kZSI6Iis5NzEiLCJvZmZpY2VfcGhvbmUiOm51bGwsInBpbl9jb2RlIjoiMTE0MTYwIiwicGFuX251bWJlciI6bnVsbCwicGFzc3BvcnRfbnVtYmVyIjoiIiwiY291bnRyeV9pc3N1ZSI6IjAiLCJwYXNzX2V4cGlyZV9kYXRlIjoiMDAwMC0wMC0wMCIsImNyZWF0aW9uX3NvdXJjZSI6InBvcnRhbCIsImNyZWF0ZWRfZGF0ZXRpbWUiOiIyMDE5LTA5LTE3IDA3OjQ0OjQ4IiwiY3JlYXRlZF9ieV9pZCI6IjAiLCJsYW5ndWFnZV9wcmVmZXJlbmNlIjoiZW5nbGlzaCIsInNpZ25hdHVyZSI6bnVsbCwic3ViX2FkbWluX3ByZXZpbGFnZSI6bnVsbCwicHJvbW9fY29kZSI6bnVsbCwiaG90ZWxfcHJvbW9fY29kZSI6bnVsbCwiY2FyX3Byb21vX2NvZGUiOm51bGwsImdyb3VwIjoiMCJ9LCJBUElfVElNRSI6MTU3MjQwMzU2Nn0.rU3NIqiHxsgOS7zeeuSCmPZP9Sc7RMXVGKWXni4JBLM"
}
}
Here is the current code that I have :
public class Login extends AppCompatActivity {
EditText username, password;
Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.username = findViewById(R.id.editTextUsername);
this.password = findViewById(R.id.editTextPassword);
this.loginButton = findViewById(R.id.buttonLogin);
this.loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(Login.this, "I just clicked the button",
Toast.LENGTH_LONG).show();
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
String URL =
"http://apidev.travelhouse.world/api/v1/user/login?
username=faisalckyf#gmail.com&password=faisal";
final JSONObject jsonBody = new JSONObject();
// jsonBody.put("username", "faisalckyf#gmail.com");
// jsonBody.put("password", "faisal");
final String requestBody = jsonBody.toString();
JsonArrayRequest jsonObjectRequest = new
JsonArrayRequest(Request.Method.POST, URL, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String token = "";
for (int i = 0; i < response.length(); i++)
{
try {
JSONObject hit =
response.getJSONObject(i);
token = hit.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(Login.this, token,
Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.toString(),
Toast.LENGTH_LONG).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null :
requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while
trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String>
parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString =
String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(response,
HttpHeaderParser.parseCacheHeaders(response));
}
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX#123");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
//
});
//
}
}
You are parsing status code instead of result token in your parseNetworkResponse() function:
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
You need to change the return statement to this:
return Response.success(response, HttpHeaderParser.parseCacheHeaders(response));
As you can see, in your function you are taking the response but you are only passing the status code(responseString) to result.
Secondly your response is actually JSON object. You need to parse it to JsonObject (or use JsonObjectRequest) and then read value token nested in result.

How to pass multiple information array and a image array to server?

I have an array which is contain image quantity for image and another is image size array which is contain image size, also an image array. I'm trying to send them to server but i failed every time. I'm trying many example but nothing was worked for me. Is there any other way to do this ? Please give me some hints or link.
how to send array of params using volley in android
public void uploadMultipleImage(String url, final List<SelectedImageModel> selectedImageModels)
{
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
responseListener.onResultSuccess(resultResponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String result = new String(networkResponse.data);
responseListener.onResultSuccess(result);
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("size["+i+"]",selectedImageModels.get(i).getPhotoSize());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("quantity["+i+"]",selectedImageModels.get(i).getPhotoQuantity());
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer "+requiredInfo.getAccessToken());
headers.put("Accept", "application/json");
headers.put("Content-Type", "x-www-form-urlencoded");
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>(selectedImageModels.size());
for(int i=0; i<selectedImageModels.size(); i++)
params.put("image["+i+"]",new DataPart("imageName",UserProfile.getFileDataFromDrawable(selectedImageModels.get(i).getPhoto())));
return params;
}
};
requestQueue.add(multipartRequest);
}
Every time i'm getting com.android.volley.server error 500 this error
Make a method for send array of params.
private String makeJsonObjectParams() {
//In mediaData,I am sending image to AWS and I will get the download link and I
// am storing the downloadurl in downloadurl arrayslist.
JSONArray mediaData = new JSONArray();
try {
if(img1 != 1) {
JSONObject temp = new JSONObject();
temp.put("file", download_url.get(0));
temp.put("type", "signature");
mediaData.put(temp);
}
if(img2 != 1){
JSONObject temp1 = new JSONObject();
temp1.put("file", download_url.get(1));
temp1.put("type", "id proof");
mediaData.put(temp1);
}
} catch (JSONException e) {
e.printStackTrace();
}
//for sending normal details like text
JSONObject updateDetails = new JSONObject();
try {
updateDetails.put("status", 2);
updateDetails.put("userId", sharedPreferences.getString("user_ID",""));
updateDetails.put("deviceToken", splash_screen.android_id);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonVerificationDetails = new JSONObject();
try {
jsonVerificationDetails.put("type", verificatin_type);
jsonVerificationDetails.put("durationOfStay", durationOfStay.getText().toString());
jsonVerificationDetails.put("media", mediaData);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("verificationDetails", jsonVerificationDetails);
jsonBody.put("updateDetails", updateDetails);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonBody.toString();
return mRequestBody;
}
}
Through the below code send the code to server.
void submitData(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
final String mRequestBody = makeJsonObjectParams();
StringRequest stringRequest = new StringRequest(Request.Method.POST, completedTaskUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//do whatever you want
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
// return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
return super.parseNetworkResponse(response);
}
};
requestQueue=Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
} catch (Exception e) {//JSONException e
e.printStackTrace();
}
}

Android Volley onResponse get data

In a string post request for logging in. in onResponse all i am returned is the status code of 200. I would like to get the data returned as well. I am not sure where to go from this point forward? Any ideas on how to get the data returned, and not just the status code?
public void requestWithSomeHttpHeaders() {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://......";
JSONObject jsonBody = new JSONObject();
jsonBody.put("username", "yourusername");
jsonBody.put("password", "yourpassword");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
System.out.println(responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Preferably, define a method.
private void doLogin() {
// TODO: startActivity?
}
Then call that
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
doLogin();
}
If you want the data from the server, that is what String response is. Check your Logcat.
As mentioned in the comments, using StringRequest without implementing getBody, parseNetworkResponse, and getBodyContentType might work better.
If you want to parse JSON add method like this
public Profile getUserProfile(String response){
Profile profile = null;
try {
profile = new Profile();
JSONObject jsonObject = new JSONObject(response);
profile.setId(jsonObject.getInt(context.getString(R.string.profile_id)));
profile.setLastName(jsonObject.getString(context.getString(R.string.profile_lastName)));
profile.setName(jsonObject.getString(context.getString(R.string.profile_name)));
profile.setEmail(jsonObject.getString(context.getString(R.string.profile_email)));
} catch (JSONException | NullPointerException e) {
e.printStackTrace();
return null;
}
return profile;
}
In your onResponse method
#Override
public void onResponse(String response) {
//If you have son object
Profile profile = getUserProfile(response)
}

How I send a JsonObject and recive a JsonArray

While I was testing the "volley" library, a doubt arose me regarding the method "post".
The thing is that I have been working with JsonObject until now, for that I used the following code and it works. In this method I send and JsonObject and receive another JsonObjet, I had no problem with it.
Now my doubt is, How can I do to send a JsonObject and receive an ArrayObject?
I am really lost with this, I will really appreciate your help, thanks in advance
public void testPost(String url, final String tag, JSONObject obj) {
//final ProgressDialog pDialog = new ProgressDialog(context);
//pDialog.setMessage("Loading...");
//pDialog.show();
JsonObjectRequest jsonObjReqpost = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//test
Log.d("SendRequestJsonPost", response.toString());
//pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.data != null) {
error = new VolleyError(new String(error.networkResponse.data));
}
String fail = handlingErrors.resolverErrors(error.toString());
//Log.d("SendRequestJsonPost", fail);
//pDialog.hide();
}
}) {
//header
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("charset", "utf-8");
return headers;
}
};
jsonObjReqpost.setTag(tag);
Singleton.getInstance(context).addToRequestQueue(jsonObjReqpost);
}
You can use the following method to get JsonArray as response.
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener)
{
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(),
listener, errorListener);
}
Please refer this answer for more details.
public class nameOfClass extends AsyncTask {
String response;
//This process is work in Background
#Override
protected String doInBackground(String... params) {
SocketConnection connection = new SocketConnection();
String token;
//Tocken name that is send to server
token = "TockenName|" + "|";
try {
response = connection.EstablishConnection(token);
String message = "Sorry Fail to connect";
if (response.equals(message)) {
onPostExecute(message);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// In this method you can open loading msg
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
//Json object
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
//Hear traverse the loop and get the data
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Android Volley multiple Requests

I try to execute a new volley request in the current volley request, but when the new request is called it don't step into the onrespond method.
The new request should be executed before the first ends. (Last in, first out)
How can I execute the new request succesfully ?
private void makeJsonObjectRequest() {
ac = new AppController();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("test", response.toString());
try {
// Parsing json object response
// response will be a json object
JSONArray name = response.getJSONArray("data");
for (int i = 0; i < name.length(); i++) {
JSONObject post = (JSONObject) name.getJSONObject(i);
try {
objectid = post.getString("object_id");
newRequest(objectid);
}
catch (Exception e) {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("test", "Error: " + error.getMessage());
}
});
// Adding request to request queue
ac.getInstance().addToRequestQueue(jsonObjReq);
}
Try it Work 100%
public class Utility {
String result = "";
String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
this.context = context;
}
public String getString(String url, final VolleyCallback callback) {
showpDialog();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = response;
hideDialog();
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onRequestError(error);
hideDialog();
/*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
((Activity) context).setContentView(layout);*/
}
});
VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
stringRequest.setRetryPolicy(
new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
return result;
}
public interface VolleyCallback {
void onSuccess(String result);
void onRequestError(VolleyError errorMessage);
//void onJsonInvoke(String url, final VolleyCallback callback);
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
private void showpDialog() {
onProgress();
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public void onProgress() {
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
Call Fragment
Utility utility = new Utility(getContext());
utility.getString(urls, new Utility.VolleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject toplinks = new JSONObject(result);
JSONObject data = toplinks.getJSONObject("toplinks");
M.i("============LS", "" + data);
} catch (JSONException e) {
e.printStackTrace();
}
finally {
}
}
#Override
public void onRequestError(VolleyError errorMessage) {
errorJson.setVisibility(View.VISIBLE);
String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
errorJson.setText(msg);
}
});
all this about
Request Prioritization
Networking calls is real time operation so let consider we have multi request like in your case , Volley processes the requests from higher priorities to lower priorities , in first-in-first-out order.
So all you need change priority (set Priority.HIGH) to request you want process first.
here is a piece of code
public class CustomPriorityRequest extends JsonObjectRequest {
// default value
Priority mPriority = Priority.HIGH;
public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority p){
mPriority = p;
}
}
As others mentioned one way is to put a high priority on the request.
Another option as it seems you have the first request depending on the inner one wrapped in the try-catch block which seems to me you want to achieve a synchronous/blocking behavior for this specific case. then you can use RequestFuture :
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = newRequest(objectid, future);
requestQueue.add(request);
String result = future.get();

Categories

Resources