Android Volley error in POST request. - android

I have a problem with my Android code. I use volley lib to make http requests. In order to login into my app, I use the code below:
private void checkLogin(final String email_string, final String password_string) {
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
session.setLogin(true);
/*
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user.getString("created_at");
db.addUser(name, email, uid, created_at);
*/
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
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
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=utf-8";
}
/*
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Accept-Charset:", "charset=utf-8");
headers.put("Content-type", "application/x-www-form-urlencoded");
return headers;
}
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("email", email_string);
params.put("password", password_string);
return params;
}
};
int socketTimeout = 10000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 1, 1);
strReq.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
My API for logging in is the below piece of code:
$app->post('/login', function() use ($app) {
// check for required params
verifyRequiredParams(array('email', 'password'));
// reading post params
$email = $app->request()->post('email');
$password = $app->request()->post('password');
$response = array();
$db = new DbHandler();
// check for correct email and password
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["error"] = false;
$response['name'] = $user['name'];
$response['email'] = $user['email'];
$response['apiKey'] = $user['api_key'];
$response['createdAt'] = $user['created_at'];
} else {
// unknown error occurred
$response['error'] = true;
$response['message'] = "An error occurred. Please try again";
}
} else {
// user credentials are wrong
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
}
echoRespnse(200, $response);
});
public function checkLogin($email, $password) {
// fetching user by email
$stmt = $this->conn->prepare("SELECT password_hash FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($password_hash);
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Found user with the email
// Now verify the password
$stmt->fetch();
$stmt->close();
if (PassHash::check_password($password_hash, $password)) {
// User password is correct
return TRUE;
} else {
// user password is incorrect
return FALSE;
}
} else {
$stmt->close();
// user not existed with the email
return FALSE;
}
}
When I try and use postman to check my API, and POST the params in the URL, I get the correct response from my API. Therefore, I think there is no problem with it. However, when I try my Android code, it always returns me incorrect credentials. I am sure I've added the correct params. I think the problem is somewhere in my headers. Do you have any suggestions that could fix it?

Related

There is no applicable constructor? Error appears on POST method in volley

I am making registration activity in android with volley but i get some error in post method please help
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
I am using volley:library-aar:1.0.0
And AppConfig.java
public class AppConfig {
public static String URL_REGISTER = "";
}
Error is
There is no applicable constructor to '(int.java.lang.string, com.andro.login.RegisterActivity.(anonymous), com.andro.login.RegisterActivity.(anonymous))'
Any solution for this prob?

app returning empty Toast

i am getting an empty Toast as response when i try to register a user to my sql database and no useful error hint is thrown in the logcat.
please what could possibly be the cause of this ?
registerProcess
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, 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");
if (!error) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
web service
/**
* Adding new user to mysql database
* returns user details
*/
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
There seems to be no error in the code, as far as I can see.
You should check the response you get with curl and see, what is returned.
to get the response from your web service you don't need JSON since you're doing a POST request by Volley. Your toast is empty because simply you're interpreting the response wrong and the objects like this one String errorMsg = jObj.getString("message"); will be empty.
To get the response you should do like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
EDIT :
I managed to spot two things in your web service code.
1- why are you trying to get informations from the server of the same user when you just sent them from your app. That doesn't make sense. You should attach your data as extra to your intent as you did with the email.
2- Volley expects a String type response and you giving him different formats at the same time.
So this a modified version of your code :
Web service :
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
echo "successful";
} else {
echo "notsuccessful";
}
}
Android
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
if (response.equalsIgnoreCase("successful")) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
//add other informations you need like name ect..
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else if(response.equalsIgnoreCase("notsuccessful")) {
Toast.makeText(getApplicationContext(),"new user wasn't registered successfully", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
NOTE :
if you wanna know the error from your Mysql request don't show it on your app, just check it in your browser.
I hope this works for you

Unable to get profile pic url from Mysql Database in Android

in my Database, I have profile pic URL. I want to get profile pic URL along with user details and display in my app. below is my JSON response.
{"error":false,"userid":"102372118524277056034","uname":"Asesha G","ulocation":"Location Not Set"
,"ugend":"Not Set","uemail":"asesha4u#gmail.com","oarth":"Google","propic":"https:\/\/lh3.googleusercontent
.com\/-JHsviYEvBU4\/AAAAAAAAAAI\/AAAAAAAAAAA\/SiDYHY21SSA\/s64-c\/102372118524277056034.jpg"}
in my response the URL is
propic":"https:\/\/lh3.googleusercontent
.com\/-JHsviYEvBU4\/AAAAAAAAAAI\/AAAAAAAAAAA\/SiDYHY21SSA\/s64-c\/102372118524277056034.jpg
in my activity, I am getting all user details except URL. below is my data type for getting profile pic URL.
private void SetsessionValues(final String userid) {
String tag_string_req = "fetch_login_data";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppURLs.fetch_data_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String userId = jObj.getString("userid");
String uname = jObj.getString("uname");
String ulocation = jObj.getString("ulocation");
String ugend = jObj.getString("ugend");
String uemail = jObj.getString("uemail");
String oarth = jObj.getString("oarth");
String profilepic = jObj.getString("propic");
Log.e(TAG,"Profile Pic : "+profilepic);
session.setLogin(true);
session.setMember(userId, uname, ulocation, ugend, uemail, oarth, profilepic);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Post params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login_data");
params.put("username", userid);
return params;
}
};
// Adding request to queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
getting null in profilepic
logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at libcore.net.UriCodec.encode(UriCodec.java:132)
at java.net.URLEncoder.encode(URLEncoder.java:57)
at com.android.volley.Request.encodeParameters(Request.java:484)
at com.android.volley.Request.getBody(Request.java:470)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:253)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:227)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
my php code for JSON
if($tag == 'login_data'){
$userid=$_POST['username'];
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql=$dbh->prepare("SELECT * FROM member WHERE oauth_uid=?");
$sql->bindValue(1,$userid);
$sql->execute();
if ($sql->rowCount() > 0) {
// user stored successfully
$userrow = $sql->fetch(PDO::FETCH_ASSOC);
$response["error"] = FALSE;
$response["userid"]= $userrow['oauth_uid'];
$response["uname"]= ucwords(strtolower($userrow['mname']));
$response["ulocation"]= $userrow['location'];
$response["ugend"]= $userrow['gender'];
$response["uemail"]= $userrow['email'];
$response["oarth"]= $userrow['oauth_provider'];
$response["propic"]= $userrow['propic'];
header('Content-Type:Application/json');
//$array[] = $response;
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Getting Personal Data";
echo json_encode($response);
}
}
}
To remove backslash just add below line after String profilepic = jObj.getString("propic");:
profilepic = profilepic.replace("\\","");

Get Org.json.JSONException:Value array(2) of type java.lang.String can not be converted to JSONObject

In my android app, I want to insert data from database using php script. Php script is there , data should be successfully fetched from database and insert into database but in android side , getting error value array(2) of type java.lang.String .
function.php
public function StoreListInfo($list_name,$list_title)
{
$stmt = $this->conn->prepare("INSERT INTO ibeSaveList(list_name,list_title) VALUES(?,?)");
$stmt->bind_param("ss", $list_name, $list_title);
$result = $stmt->execute();
$stmt->close();
if($result)
{
$stmt = $this->conn->prepare("SELECT list_name,list_title FROM ibeSaveList WHERE list_title = ?");
$stmt->bind_param("s",$list_title);
$stmt->execute();
$stmt->bind_result($token2,$token3);
while( $stmt->fetch() )
{
$user["list_name"]=$token2;
$user["list_title"]=$token3;
}
$stmt->close();
return $user;
}
else
{
return false;
}
}
StoreListInfo() which is called in web service.php
WebService.php
<?php
require_once 'update_user_info.php';
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
var_dump($_POST);
if (isset($_POST['list_name']) && isset($_POST['list_title'])) {
// receiving the post params
$list_name = $_POST['list_name'];
$list_title = $_POST['list_title'];
// create a new user
$user = $db->StoreListInfo($list_name,$list_title);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["list_name"] = $user["list_name"];
$response["user"]["list_title"] = $user["list_title"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (listname,listtitle) is missing!";
echo json_encode($response);
}
?>
list.java
private void createListUser(final String list_name, final String list_title) {
// Tag used to cancel the request
String cancel_req_tag = "createlist";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_LIST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "CreateList Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// boolean status= jObj.getBoolean("status");
if (!error) {
Intent intent = new Intent(getActivity(),
EventDetailActivity.class);
startActivity(intent);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "List Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("list_name", list_name);
params.put("list_title", list_title);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
In android output
The response that you are getting at android side doesn't seem to be valid. The response should just be this: {"error":false,"user":{"list_name":"test","list_title":"test"}}.
The response you are getting is this:
array(2) {
["list_name"] =>
string(4) "test"
["list_title"] =>
string(4) "test"
}
{"error":false,"user":{"list_name":"test","list_title":"test"}}
The response you are getting contains some more information just before the actual response as you can see in the logcat. That means you have some issue on the php side.
This should not be there:
array(2) {
["list_name"] =>
string(4) "test"
["list_title"] =>
string(4) "test"
}
Also you should set the content type header before doing echo
header('Content-Type: application/json');
Check this : Returning JSON from a PHP Script

Android volley gives BasicNetwork.performRequest: Unexpected response code 415

While doing a POST request with android volley, My serverside consumes json type in request header, I am facing error 415. Though i have set the headers here by overriding getHeaders method, I am facing this unusual error while making the request.
can any body help me here?
I have also provided the source code below:
private void registerUser( final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
//params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
#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");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

Categories

Resources