0

I am trying to login and it is giving me JSONExceptionError. Below is my login code. If I put localhost in my php code it works, but for this IP address its not working.

public class MainActivity extends AppCompatActivity  {

TextView textView;
Button login_button;
EditText Username,Password;
String username,password;
String login_url = "http://192.168.0.21/maps/login.php";
AlertDialog.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView)findViewById(R.id.reg_txt);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this,Register.class);
            startActivity(intent);
        }
    });
    builder = new AlertDialog.Builder(MainActivity.this);
    login_button = (Button)findViewById(R.id.bn_login);
    Username = (EditText)findViewById(R.id.login_name);
    Password = (EditText)findViewById(R.id.login_password);
    login_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             username = Username.getText().toString();
             password = Password.getText().toString();
            if(username.equals("")||password.equals("")){
                builder.setTitle("Something went wrong");
                displayAlert("Enter a valid username and password");
            }
            else{
                StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");
                            if(code.equals("login_failed")){
                                builder.setTitle("Error in login");
                                displayAlert(jsonObject.getString("message"));
                            }
                            else{
                                startActivity(new Intent(MainActivity.this,MapsActivity.class));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){
                  @Override
                  protected Map<String,String> getParams() throws AuthFailureError{
                      Map<String,String> params = new HashMap<>();
                      params.put("user_name",username);
                      params.put("password",password);
                    return params;
                  }
                };
                MySingeleton.getInstance(MainActivity.this).addToRequestque(stringRequest);
            }
        }
    });
}
public void displayAlert(String message){
    builder.setMessage(message);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Username.setText("");
            Password.setText("");
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}
}

Below is my php connection code. After running in browser it is giving the output but data is not getting inserted into the database.

<?php
header('Content-Type: application/json');
$host = "";
$user_name = "android";
$user_password = "^AndroidReg2019";
$db_name = "mapdb";

$conn = mysqli_connect($host,$user_name,$user_password,$db_name);

if($conn)
echo "Connection success..";
else
echo "Connection failed...";
?>

Below is my login php code.

<?php
require "init.php";
$user_name = $_POST["user_name"];
$password = $_POST["password"];
$sql = "select user_name from user_info where user_name = '$user_name' and password = '$password';";
$result = mysqli_query($conn,$sql);
$response = array();
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_row($result);
$name  = $row[0];
$code = "login_success";
array_push($response,array("code"=>$code,"user_name"=>$user_name));
echo json_encode($response);
}
else{
$code = "login_failed";
$message = "Please verify credentials and try login again.";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode($response);
}
mysqli_close($conn);
?>
15
  • Is the link 192.168.0.21/maps/login.php working in POSTMAN/ any other REST services tool? Commented Dec 2, 2019 at 5:46
  • yes. its working. Commented Dec 2, 2019 at 5:47
  • Can you send me the Json you are sending it to the link? Commented Dec 2, 2019 at 5:48
  • No i meant the values you are sending via post Commented Dec 2, 2019 at 5:49
  • name=a&email=a&user_name=a&password=a Commented Dec 2, 2019 at 5:52

2 Answers 2

2

Problem is in these line

JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0)

Your data is already a JSONObject. No need to convert response to Array and get Object.

Simple do this:

JSONObject jsonObject = new JSONObject(response);
Sign up to request clarification or add additional context in comments.

1 Comment

You answer is spot on, But the problems what she is facing is connection to her SQL, Some what PHP connection issue with MYSQL
1

Here are few of my observations below

  • You are parsing name in the param you have mentioned in the code
  • You are parsing only

params.put("user_name",username); params.put("password",password);

  • Also try to trim your username and password to make sure you are not parsing unnecessary spaces in between
  • last option try to put localhost in $host = ""; means $host = "localhost"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.