Send Object as Data with POST Method in Android Volley? - android

I am using POST method and trying to Send Object as data using Android Volley Library to change the Current Password to New One but I am not Able to do it.
SettingFragment
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
/*
// JSONObject js = new JSONObject();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = 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());
// error.getMessage();
}
}) {
#Override
public String getBodyContentType() {
return "Content-Type;application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() throws AuthFailureError {
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(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
*/
// JSONObject params = new JSONObject();
// params.put(KEY_Name, Name);
// params.put(KEY_MasterID, master_id);
// params.put(KEY_USERNAME, username);
// params.put(KEY_OldPASSWORD, oldpassword);
// params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
// headers.put(KEY_Name, Name);
// headers.put(KEY_MasterID, master_id);
// headers.put(KEY_USERNAME, username);
// headers.put(KEY_OldPASSWORD, oldpassword);
// headers.put(KEY_UserPassword, newpassword);
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Backend object looks like
Users = {
NAME: vm.name,
UserName: vm.currentUserName,
oldPassword:vm.oldPassword,
UserPassword: vm.UserPassword
Users.MasterID = vm.masterID;
}
I am able to send through the POSTMan but through Code i am not able to do it.
logcat
05-29 16:16:49.764 1114-2077/com.example.user.mis E/Volley: [651] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.100.5:84/api/usersApi/updateByMasterID
How can this issue be Solved?

You may try this code, I have implemented the same thing as you do ... it might work for you
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put(KEY_Name, Name);
headers.put(KEY_MasterID, master_id);
headers.put(KEY_USERNAME, username);
headers.put(KEY_OldPASSWORD, oldpassword);
headers.put(KEY_UserPassword, newpassword);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}

You can try this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put(KEY_USERNAME, username);
jsonBody.put(KEY_OldPASSWORD, oldpassword);
jsonBody.put(KEY_UserPassword, newpassword);
jsonBody.put(KEY_MasterID, master_id);
jsonBody.put(KEY_Name, Name);
final String requestBody = 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 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(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}

You should change the StringRequest to JSONObjectRequest as you are working with a JSON object in the backend. So you should pass the strings as a JSON object and then it might work.
private void makeJsonObjectRequest() throws JSONException {
JSONObject cred = new JSONObject();
cred.put("username", username.getText().toString());
cred.put("password", password.getText().toString());
JsonObjectRequest jsonObjReq = new
JsonObjectRequest(Request.Method.POST,
urlJsonPost, cred, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
//aftererror:
try {
// Parsing json object response
// response will be a json object
token = response.getString("token");
adminName = response.getString("adminName");
jsonResponse = "";
jsonResponse += "token:" + token ;
jsonResponse += "adminName:" + adminName;
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}});AppController.getInstance().addToRequestQueue(jsonObjReq);
You would also need to create a class named AppController.java and punch in the below code
import android.app.Application;
import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

You can also send POST parameters as JSONObject with the StringRequest.
Try this one:
private static final String KEY_Name = "NAME"
private static final String KEY_MasterID = "MasterID"
private static final String KEY_USERNAME = "UserName"
private static final String KEY_OldPASSWORD = "oldPassword"
private static final String KEY_UserPassword= "UserPassword"
..........
..................
JSONObject params = new JSONObject();
params.put(KEY_Name, Name);
params.put(KEY_MasterID, master_id);
params.put(KEY_USERNAME, username);
params.put(KEY_OldPASSWORD, oldpassword);
params.put(KEY_UserPassword, newpassword);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Navigation_URL_SettingRequest, params,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
// VolleyLog.v("Response:%n %s", response.toString(4));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
..............
...................

I have broken masterID and Send only the integer for the login, but in the changing password i want all the masterID without broken.Which is not added by me,thats the error and has to sent through the parameter section.
working code is shown below
public class SettingFragment extends Fragment implements View.OnClickListener {
EditText userName, oldPassword, newPassword;
String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
String username, oldpassword, newpassword;
String master_id, Name, access_token;
Button save, reset;
public static final String KEY_Name = "NAME";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_OldPASSWORD = "oldPassword";
public static final String KEY_UserPassword = "UserPassword";
public static final String KEY_MasterID = "MasterID";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_setting, container, false);
setHasOptionsMenu(true);
userName = (EditText) view.findViewById(R.id.setting_username);
oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
save = (Button) view.findViewById(R.id.setting_save);
reset = (Button) view.findViewById(R.id.setting_reset);
SessionManagement session = new SessionManagement(getContext());
session.checkLogin();
access_token = session.getAccesstToken();
master_id = session.getMasterId1();
System.out.println(master_id);
Name = session.getKeyName();
save.setOnClickListener(this);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
private void makeJsonSettingRequest() throws JSONException {
username = userName.getText().toString().trim();
oldpassword = oldPassword.getText().toString().trim();
newpassword = newPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("This is an Error mate");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// headers.put("Authorization", "Bearer " + access_token);
// headers.put("Authorization", access_token);
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
//JSONObject content = new JSONObject();
try {
map.put(KEY_USERNAME, username);
map.put(KEY_OldPASSWORD, oldpassword);
map.put(KEY_UserPassword, newpassword);
map.put(KEY_MasterID, "s" + master_id);
map.put(KEY_Name, Name);
Log.d("Success", map.put(KEY_USERNAME, username));
Toast.makeText(getContext(), "", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
//map.put("access_token", accesstoken);
// map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
try {
makeJsonSettingRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Related

Nodejs req.body shows empty from Android Volley

Android Code:
private void registerUser(){
final String username = "subrata";
final String password = "banerjee";
final String email = "test_email";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.
Call this method in OnResponse GetResponse(response);
And the method will be
private void GetResponse(String res){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(res);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String temp = jo.getString("what_ever");
String temp1 = jo.getString("what_ever_1");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This will get you the response in String format fetched from json.
private void registerUser(){
JSONObject jsonBodyObj = new JSONObject();
try{
jsonBodyObj.put("mAtt", "+1");
jsonBodyObj.put("mDatum","+2");
jsonBodyObj.put("mRID","+3");
jsonBodyObj.put("mVon","+4");
}catch (JSONException e){
e.printStackTrace();
}
final String requestBody = jsonBodyObj.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
return headers;
}
#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;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

How to put Cookie session id into volley request?

So, i have this code to make a POST request with volley:
public class MainActivity extends AppCompatActivity {
Button btnSearch;
ProgressDialog loadingDialog;
ListView lvResult;
String session_id;
RequestQueue queue;
MyCookieManager myCookieManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch = (Button) findViewById(R.id.btnSearch);
lvResult = (ListView) findViewById(R.id.lvResult);
loadingDialog = new ProgressDialog(MainActivity.this);
loadingDialog.setMessage("Wait.\nLoading...");
loadingDialog.setCancelable(false);
myCookieManager = new MyCookieManager();
requestCookie(); //FIRST CALL TO GET SESSION ID
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showLoading();
requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
}
});
}
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
//
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap < String, String > ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
//"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
return params;
}
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(postRequest);
}
public void requestWithSomeHttpHeaders() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
Log.d("Response", response);
String x = myCookieManager.getCookieValue();
String status = "";
try {
JSONObject resultObject = new JSONObject(response);
Log.d("JSON RESULT =>", resultObject.toString());
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
hideLoading();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map <String, String> getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap <String, String> ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
return params;
}
};
queue.add(postRequest);
}
private void showLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!loadingDialog.isShowing())
loadingDialog.show();
}
});
}
private void hideLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loadingDialog.isShowing())
loadingDialog.dismiss();
}
});
}
}
If I send a valid cookie ID this return a valid JSON object else a empty object.
I tried (unsuccessfully) to set default cookie handles like
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
but I get a empty object.
How to put a valid cookie session ID to post request?
So the problem was getting a valid cookie. My mistake was to get it from the POST request itself. I kept the same working principle, getting the cookie when I started the application but using GET instead of POST and calling the root of the URL instead of the address where I get the JSON.
My solution looked like this:
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(getRequest);
}
Using cookies with Android volley library
Request class:
public class StringRequest extends com.android.volley.toolbox.StringRequest {
private final Map<String, String> _params;
/**
* #param method
* #param url
* #param params
* A {#link HashMap} to post with the request. Null is allowed
* and indicates no parameters will be posted along with request.
* #param listener
* #param errorListener
*/
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, listener, errorListener);
_params = params;
}
#Override
protected Map<String, String> getParams() {
return _params;
}
/* (non-Javadoc)
* #see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
*/
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
MyApp.get().checkSessionCookie(response.headers);
return super.parseNetworkResponse(response);
}
/* (non-Javadoc)
* #see com.android.volley.Request#getHeaders()
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
}
MyApp:
public class MyApp extends Application {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
private static MyApp _instance;
private RequestQueue _requestQueue;
private SharedPreferences _preferences;
public static MyApp get() {
return _instance;
}
#Override
public void onCreate() {
super.onCreate();
_instance = this;
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_requestQueue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return _requestQueue;
}
/**
* Checks the response headers for session cookie and saves it
* if it finds it.
* #param headers Response Headers.
*/
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
}
You getting cookie (Session id) in Login response, Save cookie in sharedpreference or other db, and use that to send in request.
for getting cookie from login request
CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.POST, SIGN_IN_URL,
new Response.Listener<CustomStringRequest.ResponseM>() {
#Override
public void onResponse(CustomStringRequest.ResponseM result) {
CookieManager cookieManage = new CookieManager();
CookieHandler.setDefault(cookieManage);
progressDialog.hide();
try {
//From here you will get headers
String sessionId = result.headers.get("Set-Cookie");
String responseString = result.response;
Log.e("session", sessionId);
Log.e("responseString", responseString);
JSONObject object = new JSONObject(responseString);
CustomStringRequest class
public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {
private Response.Listener<CustomStringRequest.ResponseM> mListener;
public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = responseListener;
}
#Override
protected void deliverResponse(ResponseM response) {
this.mListener.onResponse(response);
}
#Override
protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
ResponseM responseM = new ResponseM();
responseM.headers = response.headers;
responseM.response = parsed;
return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
}
public static class ResponseM {
public Map<String, String> headers;
public String response;
}
}
set cookie when add request to server..
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String session=sharedPreferences.getString("sessionId","");
headers.put("Cookie",session);
return headers;
}

How do I send a POST request using Volley

So I have this customer, and I want to update the fcm_token value in the customer object via post request using volley, but It's not working..!
See the json link >> http://www.mocky.io/v2/5911638a1200001e020fb5d2
My attempt so far..
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
Customer me = Hawk.get("user");
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
.POST, URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//Log
}
}
);
requestQueue.add(jsObjRequest);
UPDATE
I change request to this and still didn't change..!?
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(jsonObjReq);
UPDATE 2
so after a lot of attempts still not solved, but I'm gonna explain what I want to do exactly maybe you will get what I want to accomplish, I wanna send my device fcm token to server based on the user id when login, so I have a Customer model class that has the value of fcm_token it must after the request is made it must be set as my token, the process happens in web server btw.
Here's my code so far..
MyFirebaseInstanceIDService Class
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
String refreshedToken;
#Override
public void onTokenRefresh() {
refreshedToken = FirebaseInstanceId.getInstance().getToken();
Hawk.put("token", refreshedToken);
}
public static void sendRegistrationToServer(Context context) {
}
}
Customer Model Class
public class Customer {
#SerializedName("avatar_url")
#Expose
private String cusPicURL;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("fcm_token")
#Expose
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
// ..... more variables & setters and getters
My Request Code inside a repository class (all request are here..)
public static void UpdateFCM_Token(final Context context, final String token) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
Customer me = Hawk.get("user");
Log.i("USER ID: ", "" + me.getID());
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject o = response.getJSONObject("customer");
Gson gson = new Gson();
Customer customer = gson.fromJson(o.toString(), Customer.class);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("FCM OnResponse", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("FCM Error: ", "" + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(req);
}
The fragment in MainActivity
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// code..
String token = Hawk.get("token");
Log.i("TOKEN", token);
DriverRepository.UpdateFCM_Token(getActivity(), token);
return rootView;
}
The Logs
Hey you suppose to add Map + remove null from new JsonObjectRequest(.......null,listener....):
private void sendRegistrationToServer(String token) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
Customer me = Hawk.get("user");
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//Log
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> map = new HashMap();
//add your params here to the map
return map;
}
};
requestQueue.add(jsObjRequest);
You may have to override getParams of JsonObjectRequest and pass your POST params.
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
.POST, URL, null, listener, errorListener){
protected Map<String,String> getParams() throws AuthFailureError{
return postParamsMap;
}
}
You can also use StringRequest instead of JsonObjectRequest.
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
//Converting the response to JSON
JSONObject jsonObj = new JSONObject(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(jsonObjReq);
after some works, I solved it using okhttp3 since volley didn't work for me, although the rest of request in my app are using volley but this one is only okhttp3, I hope that's not a bad practice.
Thanks a lot guys for ur help..!
here's the code in my request method.. in case someone might have the same problem.
public static void UpdateFCM_Token(final String token) {
Customer me = Hawk.get("user");
Log.i("USER ID: ", "" + me.getID());
String URL = API_URLs.TokenURL(me.getID());
OkHttpClient client = new OkHttpClient();
String json = "{\"fcm_token\":\"" + token + "\"}";
Log.i("Json : ", json);
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, json);
okhttp3.Request request = new okhttp3.Request.Builder()
.url(URL)
.post(body)
.addHeader("content-type", "application/json")
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
isTokenSent = true;
Log.i("response ", response + "");
} catch (IOException e) {
e.printStackTrace();
Log.i("IOException", "" + e);
}
}

How open a new Activity on a onResponse of Volley

I try to open a new activity on a onResponse of Volley. But I have no idea of what parameters I can use.
Indeed my Volley request is on another class and, I think I need to pass the context of my first class on the second. But I have no idea of how I can do.
public class ConnexionActivity extends Activity{
EditText textlogin;
EditText textpassword;
Button btnConnexion;
String login;
String password;
private AllRequest req;
private PrefManager pref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connexion);
this.req = new AllRequest(getApplicationContext());
this.pref = new PrefManager(getApplicationContext());
textlogin = (EditText) findViewById(R.id.editText_login_connexion);
textpassword = (EditText) findViewById(R.id.editText_mdp_connexion);
btnConnexion = (Button) findViewById(R.id.btn_Connexion);
btnConnexion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login = textlogin.getText().toString();
password = textpassword.getText().toString();
req.TokenRequest(login, password);
}
});
}
}
And that is a part of my function that do the request Volley:
public void TokenRequest(final String login, final String password){
final StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, ressources.urlToken,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse", response);
pref = new PrefManager(context);
pref.storeIsConnect(true);
try{
JSONObject rep = new JSONObject(response);
//stockage des données
pref.storeScope(rep.getString("scope"));
pref.storeTokenType(rep.getString("token_type"));
pref.storeAccessToken(rep.getString("access_token"));
pref.storeRefreshToken(rep.getString("refresh_token"));
pref.storeExpiresIn(rep.getString("expires_in"));
}catch (JSONException e) {
e.printStackTrace();
Log.e("erreurJSON", e.getMessage());
}
//I don't know how do this part
Intent intent = new Intent(ConnexionActivity.getContext(), listMirorActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onErrorResponse", error.toString());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", login);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
// add headers <key,value>
String credentials = ressources.client_id + ":" + ressources.client_secret;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
queue.add(stringRequest);
}
public void TokenRequest(final Context context,final String login, final String password){
final StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, ressources.urlToken,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse", response);
pref = new PrefManager(context);
pref.storeIsConnect(true);
try{
JSONObject rep = new JSONObject(response);
//stockage des données
pref.storeScope(rep.getString("scope"));
pref.storeTokenType(rep.getString("token_type"));
pref.storeAccessToken(rep.getString("access_token"));
pref.storeRefreshToken(rep.getString("refresh_token"));
pref.storeExpiresIn(rep.getString("expires_in"));
}catch (JSONException e) {
e.printStackTrace();
Log.e("erreurJSON", e.getMessage());
}
//I don't know how do this part
Intent intent = new Intent(context, listMirorActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onErrorResponse", error.toString());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", login);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
// add headers <key,value>
String credentials = ressources.client_id + ":" + ressources.client_secret;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
queue.add(stringRequest);
}
and in your activity change req.TokenRequest(login, password);
with req.TokenRequest(ConnexionActivity.this,login, password);
You can also create a Context variable Context context;
and then initialized it when OnCreate() is called
context=this;
So the, when the intent is being made, do this
Intent intent = new Intent(context, listMirorActivity.class);
startActivity(intent);

How to send the string which is part of URL from volley?

It may be dumb question but i struck with this am making simple login application using volley need to post String which is part of URL like this http://xxx.xx.x./{user_id}/{passwrd} and need to get json response from server so far what i have tried is :
private void registerUser(final String s, final String s1){
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("email", s);
jsonParams.put("username", s1);
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, REGISTER_URL,new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String yog=response.toString();
Log.e("Yog",yog);
mProgressView.setVisibility(View.INVISIBLE);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,s);
params.put(KEY_PASSWORD,s1);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
and calling this method inside onclick listener don't know where am making mistake can anybody help me ?
Try this
private void postDatalogin(String Usermail, String Userpwd,
String Devicetype, String Deviceid, String osname, String version, String ip) {
/* XMl Http Post */
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = null;
List<NameValuePair> nameValuePair = null;
httpPost = new HttpPost(
Loginurl);
// Building post parameters
// key and value pair
nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", Usermail));
//nameValuePair.add(new BasicNameValuePair("device_information",Deviceinfo));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
String strRet = HttpHelper.request(response);
Log.d(strRet, "strstrRet");
try {
JSONObject jsonObjRecv = new JSONObject(strRet);
String result = jsonObjRecv.getString("status");
Log.d(result, "result");
String message = jsonObjRecv.getString("info");
Log.d(message, "message");
String userid = "", username = "", useremail;
if (result.equals("Success")) {
userid = jsonObjRecv.getString("userid");
useremail = jsonObjRecv.getString("email");
username = jsonObjRecv.getString("username");
Log.d(userid, "userid");
SharedPreferences app_preferences1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = app_preferences1.edit();
editor.putBoolean("login", true);
editor.putString("userid", userid);
editor.putString("usermaiid", useremail);
editor.commit();
hidepDialog();
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} else {
hidepDialog();
showalert(message);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
just append your password in the URL http://xxx.xx.x./myId/mypass the params can be null or no value
private ProgressDialog pDialog;
private String tag_json_obj = "jobj_req";
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
String Url="http://x/x/x/x/Login?user_email=er.naveen,tamrakar#gmail.com&password=123123123";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
Url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
mResponseTextView.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}
public class AppController extends Application {
public static final String TAG = AppController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

Categories

Resources