I'm trying to make a http-post request to my localhost server. The problem I have Is that I'm not getting any response when I make the request.
I'm doing the request from a fragment class:
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i(TAG, " Button clickde");
fLogin.setCallback(loginButton); //Let's register a callback
final RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
String url = "http://127.0.0.1/create_row.php";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, error.getMessage());
}
});
fLogin.setFacebookListener(new FacebookLogin.OnFacebookListener() {
#Override
public void onFacebookLoggedIn(JSONObject parameters) {
}
});
}
});
Nothing is printed out from the onResponse or Response.ErrorListener.
You did't add the jsObjRequest to the queue, so the request wasn't executed, add it to the queue by:
queue.add(jsObjRequest);
see the tutorial on developer.android.com.
Related
I am using volley library to send data on server as a json. My server response successfully. Data is saving in database. But Volley execute the ErrorResponse, here is my code
private void upload(final Context context) {
String url = BASE_URL + "upload.php";
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Intent intent=new Intent(ProfilePictureActivity.this,HomeActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.i("Error", "" + error);
Toast.makeText(context, "Cannot save", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> stringMap = new HashMap<>();
stringMap.put("name", names);
stringMap.put("date_of_birth",dobs);
stringMap.put("address", presentAddress);
stringMap.put("phone",phone);
stringMap.put("email", email);
stringMap.put("image",phone+".jpg");
stringMap.put("photo",imageToString(bitmap));
return stringMap;
}
};
requestQueue.add(stringRequest);
}
My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});
I am using simmilar fucntion for creating GET and POST api requests, but the GET function set textview to response body and I dont know how to read the status code and the POST function set textview to the response code and I dont know how to read response body. Can you help me, please?
I also tried to log in parseNetworkResponse() response.data.toString() but thats is not the data that api returns. Maybe I need to encode it somehow?
public void createGet(Context context, String url) {
final TextView apiResultTextview = (TextView) ((Activity)
context).findViewById(R.id.api_result_textview);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
apiResultTextview.setText("Response is: " + response.substring(0, 50));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
apiResultTextview.setText(error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void createPost(Context context, String url, JSONObject body) {
final TextView apiResultTextview = (TextView) ((Activity) context).findViewById(R.id.api_result_textview);
RequestQueue requestQueue = Volley.newRequestQueue(context);
final String mRequestBody = body.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_RESPONSE", 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);
apiResultTextview.setText("Response is: " + responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
}
I solved it by changing method for call to code below. Problem was probably in JsonObjectRequest vs StringRequest. That's why I was getting only response code string.
public void createCall(int type, String url, JSONObject data, final int callback) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(type, url,data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
callback(response, callback);
} catch (Exception e){
Log.d("API callback error", e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error response", error.toString());
}
}
);
queue.add(jsonRequest);
}
add this code in you onResponse() Method
JSONObject jsonObj = new JSONObject(response);
String response_value = jsonObj.getString("response");
I am using volley for login authentication,I passed values to the url by using JSON. Is it Correct Way? if not please tell me how to use POST and GET method in volley Library.i want to authentication to be done using volley library by passing string to the url
String loginurl = "http://www.souqalkhaleejia.com/webapis/login.php?email="+user+"&password="+pass;
Log.i("logurl", loginurl);
JsonObjectRequest loginreq = new JsonObjectRequest(Request.Method.POST, loginurl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
String lomsg = response.getString("message");
String userid = response.getString("userid");
loginsession = new Session(getApplicationContext());
loginsession.createLoginSession(user, pass);
logineditor.putString("uid", userid);
logineditor.commit();
if (rememberme.isChecked()) {
logineditor.putBoolean("saveboolean", true);
logineditor.putString("uname", user);
logineditor.putString("pass", pass);
logineditor.commit();
} else {
logineditor.clear();
logineditor.commit();
}
Intent lognext = new Intent(MainActivity.this, Homescreen.class);
startActivity(lognext);
Toast.makeText(MainActivity.this, ""+lomsg,Toast.LENGTH_SHORT).show();
} else {
String errmsg = response.getString("message");
Toast.makeText(MainActivity.this,""+errmsg,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error,Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(loginreq);
}
You should pass the params like this
RequestQueue queue = Volley.newRequestQueue(context);
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("userId", UserSingleton.getInstance(context).getUserId());
//jsonParams.put("userId", alert.getUser().getUserId());
// Request a string response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL , new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Response OK
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Error
}
});
How to send 2nd Request to server , after getting Response from Server ? Using Volley.
I get response using,
private void makeStringReq() {
showProgressDialog();
// Instantiate the Request Q
RequestQueue q=Volley.newRequestQueue(this);
StringRequest strReq = new StringRequest(Method.GET,
Const.URL_STRING_REQ, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
});
// Add the request to the RequestQueue.
q.add(strReq);
}
my question is , How to send request back once i got the response from server ?
thanks.
private void makeStringReq(String url, int method)
{
showProgressDialog();
// Instantiate the Request Q
RequestQueue q = Volley.newRequestQueue(this);
StringRequest strReq = new StringRequest(method, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
makeStringReq(URL_B,Method.POST);
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
});
// Add the request to the RequestQueue.
q.add(strReq);
}