I have a problem with my Web Service, I am trying to obtain my values that are stored in a database, but when I consult the web services from the browser it gives me the correct information which makes me think that the WbService already works, the problem is that now I want to consult it from an android application but it gives me this error:
Value Access of type java.lang.String cannot be converted to JSONObject
I don't understand this error, my Web Service is like this:
<?PHP
require( dirname(__FILE__) . '/wp-load.php' );
$hostname_localhost = "localhost";
$database_localhost = "prueba";
$username_localhost = "root";
$password_localhost = "";
$json=array();
if(isset($_GET["name_usu"])){
$nombre_usuario = $_GET["name_usu"];
$password = $_GET["password"];
include 'PasswordHash.php';
echo $pass;
$conexion = mysqli_connect($hostname_localhost, $username_localhost, $password_localhost, $database_localhost);
mysqli_set_charset($conexion, "utf8");
$consulta="SELECT ID, user, pass, nickname, email, url, fecha_registro, name_mostrar FROM usuarios WHERE user = '{$name_usu}'";
$resultado=mysqli_query($conexion,$consulta);
if($registro=mysqli_fetch_array($resultado)){
$wp_hasher = new PasswordHash(8, true); // 16 digit hashing password
$pass = $wp_hasher->HashPassword($_POST['password']); //$posted['password'] is your password
if($wp_hasher->CheckPassword( $password, $registro[2] )){
echo "Acceso correcto";
//Si todo funciona mandaremos la informacion a este array
$json['sesion'][]=$registro;
}else{
echo "El usuario es incorrecto";
}
}else{
$resultar["ID"]='No registrado';
$resultar["user"]='No registrado';
$resultar["pass"]='No registrado';
$resultar["nickname"]='No registrado';
$resultar["email"]='No registrado';
$resultar["url"]='No registrado';
$resultar["fecha_registro"]='No registrado';
$resultar["name_mostrar"]='No registrado';
$json['sesion'][]=$resultar;
}
mysqli_close($conexion);
echo json_encode($json);
}else{
$resultar["success"]=0;
$resultar["message"]='Ws no Retorna';
$json['sesion'][]=$resultar;
echo json_encode($json);
}
?>
Successful access{"session":[{"0":"1757","ID":"1757","1":"testdb","user":"testdb","2":"$P$BhbEVMLV6onULEfYLG3dsF5xuv9t9j0 ","pass":"$P$BhbEVMLV6onULEfYLG3dsF5xuv9t9j0","3":"testdb","nickname":"testdb","4":"[email protected]","email":"dbtest@outlook. com","5":"","url":"","6":"2019-02-20 15:35:53","date_registration":"2019-02-20 15:35:53" ,"7":"enrique espinosa","display_name":"enrique espinosa"}]}
And in my application I have this in the OnResponde method and in the onErrorResponse:
@Override
public void onResponse(JSONObject response) {
JSONArray json = response.optJSONArray("sesion");
JSONObject jsonObject = null;
try{
jsonObject = json.getJSONObject(0);
ID = (jsonObject.getInt("ID"));
user = (jsonObject.getString("user"));
pass = (jsonObject.getString("pass"));
//claveBD = (jsonObject.getString("clave"));
nickname = (jsonObject.getString("nickname"));
email = (jsonObject.getString("email"));
url = (jsonObject.getString("url"));
fecha_Registro = (jsonObject.getDouble("fecha_registro"));
nombre_mostrar = (jsonObject.getString("nombre_mostrar"));
//(jsonObject.getString("recordado"));
}catch (JSONException e){
e.printStackTrace();
}
if (nombreBD.equals("No registrado") || passwordBD.equals("No registrado")){
Toast.makeText(getApplicationContext(), "Los datos son incorrectos", Toast.LENGTH_LONG).show();
}else if(passwordBD.equals(passwordCaja)){
registrarUsuario(nombreBD, passwordBD,"master",rolBD, empresaBD, box);
}else {
Toast.makeText(getApplicationContext(), "La contraseña es incorrecta", Toast.LENGTH_LONG).show();
}
}
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error al conectar al servidor: "+error, Toast.LENGTH_LONG).show();
Log.i("servidor","Error de conexion: "+error);
error.printStackTrace();
}
Your code is not consistent on several points, which I will list below:
If the app expects a JSON, nothing other than JSON should ever be displayed in the PHP code . In fact if you look at the output:
Acceso correcto{"sesion":[{"0":"1757","ID":"1757","1":"bdprueba","user":"b ...
whatecho
you do out of the JSON is screwing everything up. So remove thoseecho
.Your reading of the JSON in Android is also inconsistent. For example, you try to search for an integer here:
ID = (jsonObject.getInt("ID"));
but in the JSON that value will not be recognized as an integer, because it is in quotes:"ID":"1757"
, for it to be recognized as an integer, it has to be like this in the JSON:"ID":1757
You cannot try to get any value as an integer that is between quotes, that will give an error.In Android reading the JSON there is no consistency for wrong cases. Which are also not clearly handled in PHP. For erroneous cases, I would simply make an array like this:
$arr=array ("error"=>"Mensaje de error");
and then in Android the first thing I would do would be to search if the JSON has a keyerror
to show it and if it doesn't, everything is OK and I'll go on to get what's insesion
. These types of requests have to be consistent from one side to the other and handle them in a diaphanous way, otherwise the App will crash in a situation that you have not been able to contemplate as a programmer.