I am sending server request to handle response and error i have implemented interface. I just want to know how to handle if "mResultCallBack ==null" without editing condition if(mResultCallBack!=null). code are as follow:-
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and code for interface
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (loginSessionManager.isLogin()){
cServerRequest = new CServerRequest(mResultcallBack,mContext);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put(CRequestKey.AGENT_CODE, m_szMobileNumber.trim());// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put(CRequestKey.PIN, m_szEncryptedPassword.trim());// same here as said above
Log.e(TAG,"Request::"+jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String s_szWalletURL = CAPIStorage.IREWARDS_URL + CAPIStorage.WALLET_BALANCE_URL;
cServerRequest.postWalletRequest("POST",s_szWalletURL,jsonObject);
}else {
Log.e(TAG,"Not loggedin");
}
}
});
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
if(jsonObject.getJSONArray.length() == 0) {
System.out.println("JSONArray is null");
}
else{
System.out.println("JSONArray is not null");
//parse your string here
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
This is my MainActivity, I am unable to understand and write the unit test code for this can someone help me by providing reference or the code for this problem.In the main activity I have created the methods to call the API how can I mock the API response and get the unit tests for this.
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private final String Url="https://dev-smartoffice-api.sharpb2bcloud.com/rmi/v1/checkVersion";
IResult mResultCallback = null;
public MainActivity(IResult iResult)
{
this.mResultCallback=iResult;
}
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService.getDataVolley("GETCALL",Url);
mVolleyService = new VolleyService(mResultCallback,this);
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
// mVolleyService.postDataVolley("POSTCALL", "http://localhost/androidphpmysql/registrationapi.php?apicall=login", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String request,JSONObject response) {
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
// return error;
}
};
}
}
These are my interfaces,here there are two interfaces notify-success and notify error with return type void I don't know how to use them for mocking please help me
public interface IResult {
public void notifySuccess(String requestType, JSONObject response);
public void notifyError(String requestType, VolleyError error);
}
This is my volleyservice class
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
JSONObject message;
public VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
})
{
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest( Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
message=response;
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
}){
#Override
public Map getHeaders() throws Error {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("client-type","SYNAPPX");
headers.put("client-version","1.1.0");
headers.put("operating-system", "ANDROID");
headers.put("os-version", "8.0");
return headers;
}
};
queue.add(jsonObj);
}catch(Exception e){
e.printStackTrace();
}
}
}
In my app I have an Activity LoginUserActivity that contains a button perform a connection to a web-server using JSONObject request and Volley. If the login is successfull will be launched another activity, but if it isn't I need to re-enable the button.
LoginUserActivity
public void OnLoginUtente(View view) {
final String mail = etMail.getText().toString();
final String pw = etPassword.getText().toString();
bLogin.setEnabled(false);
DBConnection connection = new DBConnection(mail, pw, getApplicationContext());
connection.doLogin();
}
doLogin()
public void doLogin() {
JSONObject obj = new JSONObject();
try {
obj.put("type", type);
obj.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(context, response.getString("Status"), Toast.LENGTH_SHORT).show();
if (response.getString("Esito").equals("true")) {
intent = new Intent(context, MainUtente.class);
context.startActivity(intent);
}else{
//I think I've to put something here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
jsonObjectRequest.setShouldCache(false);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.getCache().clear();
requestQueue.add(jsonObjectRequest);
}
I've tried different things, such as make doLogin() return a boolean and then re-enable the button from the activity or try to inflate the layout of the calling activity in the else, but neither of these worked. If possible I'd like to keep the doLogin() method void and without parameters.
LoginUserActivity
public void OnLoginUtente(View view) {
final String mail = etMail.getText().toString();
final String pw = etPassword.getText().toString();
DBConnection connection = new DBConnection(mail, pw, getApplicationContext());
connection.doLogin(this);
}
public void disableLoginButton()
{
bLogin.setEnabled(false);
}
doLogin
public void doLogin(final LoginActivity activity) {
JSONObject obj = new JSONObject();
try {
obj.put("type", type);
obj.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(context, response.getString("Status"), Toast.LENGTH_SHORT).show();
if (response.getString("Esito").equals("true")) {
new Handler(Looper.getMainLooper()).post(new Runnable(){
public void run() {
activity.disableLoginButton();
}
);
activity.disableLoginButton();
intent = new Intent(context, MainUtente.class);
context.startActivity(intent);
}else{
//I think I've to put something here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
jsonObjectRequest.setShouldCache(false);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.getCache().clear();
requestQueue.add(jsonObjectRequest);
}
You may replace new Handler(Looper.getMainLooper()).post(runnable) with activity.runOnUiThread(runnable)
When I call getData.It seems that it is hard to get the result out from the onResponse. I know it cannot work in this current way. Could anyone help me to settle this problem?
getData()
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Country_name","hi");
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(JSON_ARRAY);
Log.v("xxxxx",result.toString());
String mysh=result.toString().substring(1, result.toString().length()-1);
JSONArray jsonArray = new JSONArray(mysh);
//Calling method getCountry to get the country from the JSON Array
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Try this i think it should work
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Try that, this will help.
private void getData() {
String tag_string_req = "req_name";
spotsDialog.show();
StringRequest strReq = new StringRequest(Method.POST,
YOUR URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("YOUR ARRAY NAME");
for (int i=0;i<array.length();i++){
String result = array.getString(i).toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
});
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Happy To Help.
how to create a separate class in which define all about volley
and in another activity we directly pass URL,CONTEXT and Get Response...
First create callback interface to get result in Activity
public interface IResult {
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
}
Create a separate class with volley function to response the result through interface to activity
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
}
Then initialize callback interface into main activity
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
Now create object of VolleyService class and pass it context and callback interface
mVolleyService = new VolleyService(mResultCallback,this);
Now call the Volley method for post or get data also pass requestType which is to identify the service requester when getting result back into main activity
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
Final MainActivity
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
IResult mResultCallback = null;
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
}
Find the whole project at following link
https://github.com/PatilRohit/VolleyCallback
JsonParserVolley.java
(A separate class where we will get the response)
public class JsonParserVolley {
final String contentType = "application/json; charset=utf-8";
String JsonURL = "Your URL";
Context context;
RequestQueue requestQueue;
String jsonresponse;
private Map<String, String> header;
public JsonParserVolley(Context context) {
this.context = context;
requestQueue = Volley.newRequestQueue(context);
header = new HashMap<>();
}
public void addHeader(String key, String value) {
header.put(key, value);
}
public void executeRequest(int method, final VolleyCallback callback) {
StringRequest stringRequest = new StringRequest(method, JsonURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
jsonresponse = response;
Log.e("RES", " res::" + jsonresponse);
callback.getResponse(jsonresponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return header;
}
}
;
requestQueue.add(stringRequest);
}
public interface VolleyCallback
{
public void getResponse(String response);
}
}
MainActivity.java
(Code Snippet written in onCreate method)
final JsonParserVolley jsonParserVolley = new JsonParserVolley(this);
jsonParserVolley.addHeader("Authorization", "Your value");
jsonParserVolley.executeRequest(Request.Method.GET, new JsonParserVolley.VolleyCallback() {
#Override
public void getResponse(String response) {
jObject=response;
Log.d("VOLLEY","RES"+jObject);
parser();
}
}
);
parser() is the method where the json response obtained is used to bind with the components of the activity.
you actually missed one parameter in the above VolleyService class. You needed to include, it is,...
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null,new Response.Listener() {
/..../
}
null is the parameter should be included else it gives error
Create Listeners(since they are interface they can't be instantiated but they can be instantied as an anonymous class that implement interface) inside the activity or fragment. And Pass this instances as parameters to the Request.(StringRequest, JsonObjectRequest, or ImageRequest).
public class MainActivity extends Activity {
private static final String URI = "";
// This is like BroadcastReceiver instantiation
private Listener<JSONObject> listenerResponse = new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
// Do what you want with response
}
};
private ErrorListener listenerError = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// Do what you want with error
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Next, create a class that has request and pass this listeners to this class' request method , that's all. I don't explain this part this is same as creating a request object in any tutorials.But you can customize this class as you wish. You can create singleton RequestQueue to check priority, or set body http body parameters to this methods as paremeters.
public class NetworkHandler {
public static void requestJSON(Context context, String url, Listener<JSONObject> listenerResponse, ErrorListener listenerError) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);
Volley.newRequestQueue(context).add(jsonRequest);
}
}
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context)
{
mResultCallback = resultCallback;
mContext = context;
}
//--Post-Api---
public void postDataVolley(String url,final Map<String,String> param){
try {
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPost(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return param;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance(mContext).addToRequestQueue(sr);
}catch(Exception e){
}
}
//==Patch-Api==
public void patchDataVolley(String url,final HashMap<String,Object> param)
{
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PATCH, url, new JSONObject(param),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPatch(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
};
AppController.getInstance(mContext).addToRequestQueue(request);
}
}
public interface IResult {
void notifySuccessPost(String response);
void notifySuccessPatch(JSONObject jsonObject);
void notifyError(VolleyError error);
}
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();