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
}
});
Related
I am trying to start an JSONArrayRequests after the StringRequest has finished. The StringRequest is POST requet and the JSONArrayRequest is GET request. I want the JSONArray to start when the params of the String is uploaded so as I will be able to retrieve this data again. Below is my code:
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL_UPLOAD_IMAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (response.equals("1")) {
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++) {
try {
JSONObject object = response.getJSONObject(i);
String USER_ID = object.getString("user_id");
String POST_DATE = object.getString("post_date");
if (USER_ID.equalsIgnoreCase(CurrentUser)){
Toast.makeText(getContext(), "First if.", Toast.LENGTH_SHORT).show();
if (POST_DATE.equalsIgnoreCase(dateTime)) {
Toast.makeText(getContext(), "Second if.", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Error", error.getMessage());
}
});
requestQueue.add(arrayRequest);
requestQueue.start();
}
}catch (Exception e) {
e.printStackTrace();
Log.d("ERROR", e.getMessage().toString());
Toast.makeText(getContext(), "ERROR:"+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Nullable
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("post_author", CurrentUser);
if (!details.getText().toString().equalsIgnoreCase("")){
params.put("post_content", details.getText().toString());
params.put("post_excerpt", details.getText().toString());
}else {
params.put("post_content", "");
params.put("post_excerpt", "");
}
params.put("post_date", dateTime);
params.put("post_date_gmt", dateTime);
params.put("post_title", CurrentUser+"-"+CurrentUser+"-"+timeStampStr);
params.put("post_status", "publish");
params.put("comment_status", "closed");
params.put("ping_status", "closed");
params.put("post_name", CurrentUser+"-"+CurrentUser+"-"+timeStampStr);
params.put("post_modified", dateTime);
params.put("post_modified_gmt", dateTime);
params.put("guid", "https://www.selfcial.com/peepso-post/"+CurrentUser+"-"+CurrentUser+"-"+timeStampStr+"/");
params.put("post_type", "peepso-post");
return params;
}
};
requestQueue.add(stringRequest);
requestQueue.start();
What I tried to do is to add a RequestQueue in order to make the requests wait until the other one is finished but it didn't work. The problem I have is that when the inside request starts it doesn't find the "if" statement(namely this:(USER_ID.equals(CurrentUser) && POST_DATE.equals(dateTime)). So, what I can understand is that the second starts before the first has finished with the params. What can I do? Any answer will be appreciated!
I am trying to get the response from the server based on the data I send it, I am able to get a response from the server, but the server doesn't seem to be receiving the values in the getParams().
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Toast.makeText(getContext(), selectedUniversityItem.getmUniversityValue(), Toast.LENGTH_SHORT).show();
params.put("schoolUniversity", selectedUniversityItem.getmUniversityValue());
params.put("key", key);
return params;
}
};
queue.add(jsonRequest);
The method I would suggest in this case is to pass the parameters in the URL of your code and remove the getParams() method.
So, your modified code looks like;
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url+"?schoolUniversity="+selectedUniversityItem.getmUniversityValue()+"&key="+key,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
};
queue.add(jsonRequest);
Hopefully, this will work. Good Luck :)
My API working correctly but when i send data using android app its not inserting data.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { JSONObject jsonBody = new JSONObject();
try {
`jsonBody.put("ID", "Android Volley Demo");
jsonBody.put("Name", "BNK");
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;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
That is my API.Its working correctly.
public HttpResponseMessage Post([FromBody]Login log)
{
db.Logins.Add(log);
db.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, log);
message.Headers.Location = new Uri(Request.RequestUri + log.ID.ToString());
return message;
}
This is my Code i am Posting data but not inserting in SQL Server but when i test API by sending raw data its working correctly.
Try this:
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
Log.i("VOLLEY Response : ", ServerResponse);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("VOLLEY ErrorResponse : ", volleyError.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Name", "BNK");
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(context);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
Check this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("firstkey", "firstvalue");
jsonBody.put("secondkey", "secondobject");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
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");