how i can send and verify parameters from server using volley? - java

I try to send some parameters to the server to verify. but it doesn't include parameters in URL, I also debug and check the value of my URL but parameters are not there. so how I can do it,
the full URL is look like this "http://38.143.223.234/~wajih/foodaway/api/userlogin.php?email=a%40&device_type=Android&password=123456&device_id=af44077c-e8ec-4b0b-aadb-e322997af8de"
if I just include all values that I am sending to the server in url then it works well. but I want to send it through parameters method
public void login(){
String url = "http://38.143.223.234/~wajih/foodaway/api/userlogin.php?";
StringRequest stringRequest = new StringRequest( Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
Log.d( "response", response );
try {
//Boolean error =jsonObject.getBoolean("error");
//values[0] = values[0].replace("[", "").replace("]", "");
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("1"))
{
//activity.initializeOneSignal();
String user_response = jsonObject.getJSONObject("user_detail").toString();
manager.setLoginDetails(user_response);
OneSignal.setSubscription(true);
dialog.dismiss();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else if (jsonObject.getString("status").equals("0"))
{
dialog.dismiss();
Toast.makeText(LoginActivity.this,
jsonObject.getString("error"), Toast.LENGTH_LONG).show();
}
else {
// Error didn't get any response from server
dialog.dismiss();
Toast.makeText(LoginActivity.this, "Something went wrong!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
getWindow().clearFlags( WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE );
if (networkResponse != null) {
Log.e( "Status code", String.valueOf( networkResponse.statusCode ) );
Toast.makeText( LoginActivity.this, String.valueOf( networkResponse.statusCode ),
Toast.LENGTH_LONG ).show();
} else {
Toast.makeText( LoginActivity.this, error.toString(),
Toast.LENGTH_LONG ).show();
}
}
}){
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<>();
MyData.put("email", userEmail);
MyData.put("device_type","Android");
MyData.put("password", userPassword);
MyData.put("device_id",deviceId);
return MyData;
}
};
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy( socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT );
stringRequest.setRetryPolicy( policy );
AppController.getInstance().addToRequestQueue( stringRequest);
}

Related

How to start onResponse method after getParams has been executed with StringRequest in Android Studio Volley?

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!

volley get response returns value of type java.lang.String cannot be converted to JSONArray

i am trying to authenticate using an api.am getting an error on response, my api returns the following response and am getting the following error.
value of type java.lang.String cannot be converted to JSONArray.
kindly help, am a newbie.
this is what my api returns:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
</string>
this is my code;
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//create a StringRequest
StringRequest request = new StringRequest( Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
int i = 0;
while (i < jArray.length()) {
JSONObject json_data = jArray.getJSONObject(i);
String status = json_data.getString("status");
if (status == "True") {
Intent intent = new Intent(LoginActivity.this, ParentActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "logged in as " + user,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "wrong username or password",
Toast.LENGTH_LONG).show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!!! " + error.toString(),
Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", user);
params.put("password", pass);
return params;
}
};
//add the StringRequest to the RequestQueue
queue.add(request);
}
I was change JSONArray jArray = new JSONArray(response); to JSONObject jObject = new JSONObject(response); and JSONObject json_data = jArray.getJSONObject(i); to String json_data = jObject(i);. Try it, please.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//create a StringRequest
StringRequest request = new StringRequest( Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
int i = 0;
while (i < jArray.length()) {
String json_data = jObject(i);
String status = json_data.getString("status");
if (status == "True") {
Intent intent = new Intent(LoginActivity.this, ParentActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "logged in as " + user,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "wrong username or password",
Toast.LENGTH_LONG).show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!!! " + error.toString(),
Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", user);
params.put("password", pass);
return params;
}
};
//add the StringRequest to the RequestQueue
queue.add(request);
}
Is your API returning
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
</string>
or
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
?
If the first, then you should extract the JSON string from the XML answer before invoking "JSONArray jArray = new JSONArray(response);", and then do something like "JSONArray jArray = new JSONArray(json_part_of_the_response);".
I think your JSON array is inside XML so you have to parse your XML first using dom parser

Without toast JSON response is not working why?

I tried MYSQL, PHP JSON and VOlley request to log in to the user but when I do without toasting the final response user is not get logged in but when I use toast user gets logged in? why is it so
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
/////////////////////THIS TOAST I AM TALKING ABOUT
Toast.makeText(getApplicationContext(), jsonObject+"", Toast.LENGTH_LONG).show();
if (!jsonObject.getBoolean("error")) {
startActivity(new Intent(LoginActivity.this, MainActivity.class);
}
if(jsonObject.getBoolean("error")){
if(jsonObject.getString("message").equals("ERROR")){
startActivity(new Intent(LoginActivity.this, Verify.class);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", username);
params.put("password", password);
return params;
}
};
stringRequest.setShouldCache(false);
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);

String Request To Post not showing any error

I am making a post request in Android studio using string request, when I debug,i get no error. I don't get the JSON object in the code when i debug. It skips the login request and debug is ended.if I'm not doing something correct.please try and correct it
This is the JSON object
{"RESPONSECODE":200,
"RESPONSEDATA:[{"id_User":"120","FirstName":"King",
"LastName":"Dosty","Role_Id":"2","Email":"donmister5000#gmail.com","location":null,"Password":"$2y$10$fJJH6qOuhhXaDadHQhZefemBwHPZ3aHid\/WF579DwVJo8XyVGaEN6",
}],"Success":true}
This is the loginRequest java class
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
private Map<String, String> params;
public LoginRequest(String Email,String Password, Response.Listener<String> listener){
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("Email", Email);
params.put("Password", Password);
}
#Override
public Map<String, String> getParams(){
return params;
}
}
This is the login button to sent the request on click in the activity
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = emailEdt.getText().toString();
String Password = passwordEdt.getText().toString();
LoginRequest loginRequest = new LoginRequest(Email, Password,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
Log.d(TAG, jsonResponse.getString("SUCCESS"));
boolean success = jsonResponse.getBoolean("SUCCESS");
if (success)
{
Intent intent = new Intent (LoginActivity.this,MainActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();}
else {
AlertDialog.Builder builder = new
AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed").setNegativeButton("Retry", null)
.create().show();
}
}
catch (JSONException e)
{ e.printStackTrace();}}
});
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
This is the url get and the params when i debug
[ ] localhost/project/index.php/clientapinew/post_login2
0x59c3b57d NORMAL null
Email : john#gmail.com
Password: azerty
I'd suggest you ditch the LoginRequest Class, and add this method in your LoginActivity:
private void login(final String email, final String password){
String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
// JSON data
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("Email", email);
jsonObject.put("Password", password);
} catch (JSONException e){
e.printStackTrace();
}
// Json request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
LOGIN_REQUEST_URL,
jsonObject,
new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response){
//Toast.makeText(context, "Product successfully added", Toast.LENGTH_SHORT).show();
try{
//use the response JSONObject now like this log
Log.d(TAG, response.getString("Success"));
boolean success = response.getBoolean("Success");
if (success) {
//...
}
} catch (JSONException e) {
System.out.println("Error logging in");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Toast.makeText(LoginActivity.this, "Can't connect to Internet. Please check your connection.", Toast.LENGTH_LONG).show();
}
else if (error instanceof ServerError) {
Toast.makeText(LoginActivity.this, "Unable to login. Either the username or password is incorrect.", Toast.LENGTH_LONG).show();
}
else if (error instanceof ParseError) {
Toast.makeText(LoginActivity.this, "Parsing error. Please try again.", Toast.LENGTH_LONG).show();
}
else if (error instanceof NoConnectionError) {
Toast.makeText(LoginActivity.this, "Can't connect to internet. Please check your connection.", Toast.LENGTH_LONG).show();
}
else if (error instanceof TimeoutError) {
Toast.makeText(LoginActivity.this, "Connection timed out. Please check your internet connection.", Toast.LENGTH_LONG).show();
}
//Do other stuff if you want
error.printStackTrace();
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String,String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
3600,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
And then your onClick should look something like
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = emailEdt.getText().toString();
String Password = passwordEdt.getText().toString();
login(Email, Password);
}
}
Create RequestQueueSingleton.java class and use something like this:
public class RequestQueueSingleton {
private static RequestQueueSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private RequestQueueSingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized RequestQueueSingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new RequestQueueSingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
The first character in the response is ">". When it tries to run this line:
JSONObject jsonResponse = new JSONObject(response);
It can't find a JsonObject in the response and your code won't work.
My suggestion is to remove ">" from your response and try again.

value 1 of type java.lang.string cannot be converted into JSONObject

Fed up with this problem.. How to solve it.. please Help.. Everytime I run my application I get this same error again and again.. Wasted 2 days already.. please someone help to get rid of it.
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Boolean error= jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("username");
String name = user.getString("username");
String email = user.getString("password");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
Above is the Login Activity code..

Categories

Resources