0

I am creating a simple Android application connected to localhost. I have successfully created a registration page and the application can register new user without any problem. I am using Volley library to create the registration/login.

The problem is with the login function. When I fill in the login details and click login I get the error

09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at com.example.virus.bloodpressurereader.Login$1$1.onResponse(Login.java:71)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at com.example.virus.bloodpressurereader.Login$1$1.onResponse(Login.java:65)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at android.os.Looper.loop(Looper.java:148)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
09-11 13:59:16.856 16107-16107/com.example.virus.bloodpressurereader W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

my login.php file is this

<?php
require "conn.php";

$user_email = $_POST["userEmail"];
$user_password = $_POST["userPass"];

$sql = "select name, email from user_profile where email = '$user_email' and password = '$user_password'";

$result = mysqli_query($conn, $sql);

$response = array();

if(mysqli_num_rows($result) > 0){

    $row = mysqli_fetch_row($result);
    $name = $row[0];
    $email = $row[1];
    $code = "login success";

    array_push($response, array("code"=>$code, "name"=>$name, "email"=>$email));

    echo json_encode($response);


}else {

    $code = "login failed";
    $message = "user not found.. Try again";

    array_push($response, array("code"=>$code,"message"=>$message));

    echo json_encode($response);
}
mysqli_close($conn);
?>

and my login.java file is this

package com.example.virus.bloodpressurereader;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.MainThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Login extends AppCompatActivity {

EditText email, password;
Button loginUser;

String userEmail, userPassword;

String login_url = "http://192.168.0.144/login.php";

AlertDialog.Builder builder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    builder = new AlertDialog.Builder(Login.this);

    loginUser = (Button)findViewById(R.id.login_button);
    email = (EditText) findViewById(R.id.login_email);
    password = (EditText)findViewById(R.id.login_password);

    loginUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //check conditions for user email and password
            userEmail = email.getText().toString();
            userPassword = password.getText().toString();

            if(userEmail.equals("") || userPassword.equals("")){

                builder.setTitle("Something went wrong");
                displayAlert("Enter a valid email and password");
            }else {
                //authenticate from server
                StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //handle response from server

                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");

                            if (code.equals("login failed")){
                                builder.setTitle("Login error");
                                displayAlert(jsonObject.getString("message"));
                            }else {
                                Intent i = new Intent(Login.this, MainActivity.class);
                                startActivity(i);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();
                        error.printStackTrace();

                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> params = new HashMap<String, String>();
                        params.put("email", userEmail);
                        params.put("password", userPassword);
                        return params;
                    }
                };
                MySingleton.getInstance(Login.this).addToRequestque(stringRequest);
            }

        }
    });

}
//display alert
public void displayAlert(String message){
    builder.setMessage(message);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            email.setText("");
            password.setText("");
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}


//registration link
public void registerUser(View view){
    Intent i = new Intent(this, Register.class);
    startActivity(i);
}

}

If I do not key in anything in the login page and click on login, the correct alert is show however, once I key in the email and password and click on login, I get the above error.

My PHP script is working fine as I have created a dummy login.html and tested it. I get the correct response in that case.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mill3r
  • 544
  • 1
  • 10
  • 31
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Sep 11 '17 at 14:11
  • **Never store plain text passwords!** Please use ***PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html)*** to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). ***It is not necessary to [escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Sep 11 '17 at 14:12
  • Looks like response received is a plain string. Look at this API - https://developer.android.com/reference/org/json/JSONArray.html#JSONArray(java.lang.String) – Rams_QA Sep 12 '17 at 05:47

2 Answers2

0

(Posted solution on behalf of the OP).

Change

$user_email = $_POST["userEmail"]; 
$user_password = $_POST["userPass"]; 

to

$user_email = $_POST["email"]; 
$user_password = $_POST["password"];
halfer
  • 19,824
  • 17
  • 99
  • 186
0

looks like your response is in string do like this

$response['row'] = mysqli_fetch_row($result);
$response['name'] = $row[0];
$response['email'] = $row[1];
$response['code'] = "login success";
echo json_encode($response);

and same goes for else condition

Anil Shrestha
  • 1,180
  • 11
  • 16