• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

JSONException

Hello, I am new to this and I am developing a basic application in android studio: A registry of users with MySQL.
When I start the application, I enter the data (Name, Surname, Email and Password) and I touch the registration button I get the following error:

org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject>

Could someone help me solve it?

This is my java code:
https://gyazo.com/c1d41c26579af44e04a438a96ed9813b
https://gyazo.com/89f2a59839cf38e63094b31b03abe0cf

These are my .php code (saved in the htdocs folder of xampp):
connect.php: https://gyazo.com/a1959c272277e84a9b77add23e8299e1
register.php: https://gyazo.com/12473d846d82cbc3eb0375f021060b2a

Sorry for my English, I speak Spanish and I'm using the Google Tradctor.
 
Welcome to AF. It may be helpful to copy and paste your code here so the folks that know this stuff don't have to follow a bunch of links. Just put them in code tags (e.g. [code][/code]) to preserver formatting and keep it readable.

Good luck. :)
 
This is my java code:
Java:
package com.example.fdesia.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

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

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

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

public class RegisterActivity extends AppCompatActivity{

    private TextView TextViewQuestion;
    private EditText Name, Surname, Email, Password;
    private Button ButtonRegister;
    private ProgressBar ProgressBar;
    private static String URL_REGIST="http://192.168.1.40/android_register_login/register.php";

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

        TextViewQuestion = (TextView)findViewById(R.id.register_textview_question);
        TextViewQuestion.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent intent = new Intent(RegisterActivity.this , LoginActivity.class);
                startActivity(intent);
            }
        });

        ProgressBar=findViewById(R.id.register_progessbar);
        Name=findViewById(R.id.register_textinput_name2);
        Surname=findViewById(R.id.register_textinput_surname2);
        Email=findViewById(R.id.register_textinput_email12);
        Password=findViewById(R.id.register_textinput_password2);
        ButtonRegister=findViewById(R.id.register_button_register);
        ButtonRegister.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Regist();
            }
        });
    }

    private void Regist(){
        ProgressBar.setVisibility(View.VISIBLE);
        ButtonRegister.setVisibility(View.GONE);

        final String Name=this.Name.getText().toString().trim();
        final String Surname=this.Surname.getText().toString().trim();
        final String Email=this.Email.getText().toString().trim();
        final String Password=this.Password.getText().toString().trim();

        StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_REGIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                    try{
                        JSONObject jsonObject=new JSONObject(response);
                        String Success=jsonObject.getString("success");
                        if (Success.equals("1")){
                            Toast.makeText(RegisterActivity.this,"Registro exitoso", Toast.LENGTH_SHORT).show();
                        }
                    }catch (JSONException e){
                        e.printStackTrace();
                        Toast.makeText(RegisterActivity.this,"Registro fallido"+e.toString(), Toast.LENGTH_SHORT).show();
                        ProgressBar.setVisibility(View.GONE);
                        ButtonRegister.setVisibility(View.VISIBLE);
                    }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error){
                        Toast.makeText(RegisterActivity.this,"Registro fallido"+error.toString(), Toast.LENGTH_SHORT).show();
                        ProgressBar.setVisibility(View.GONE);
                        ButtonRegister.setVisibility(View.VISIBLE);
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError{
                Map<String,String>params=new HashMap<>();
                params.put("Name", Name);
                params.put("Surname", Surname);
                params.put("Email", Email);
                params.put("Password", Password);
                return super.getParams();
            }
        };
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}
 
These are my .php code (saved in the htdocs folder of xampp):

connect.php:
PHP:
<?php

$conn = mysqli_connect("localhost", "root", "root", "users");

?>

register.php:
PHP:
<?php

if ($_SERVER['REQUEST_METHOD'] =='POST'){

    $Name = $_POST['Name'];
    $Surame = $_POST['Surname'];
    $Email = $_POST['Email'];
    $Password = $_POST['Password'];

    $Password = password_hash($Password, PASSWORD_DEFAULT);

    require_once 'connect.php';

    $sql = "INSERT INTO users_table (Name, Email, Password) VALUES ('$Name', '$Email', '$Password')";

    if ( mysqli_query($conn, $sql) ) {
        $result["success"] = "1";
        $result["message"] = "success";

        echo json_encode($result);
        mysqli_close($conn);

    } else {

        $result["success"] = "0";
        $result["message"] = "error";

        echo json_encode($Result);
        mysqli_close($conn);
    }
}

?>
 
Run your app in debug mode and set a breakpoint at line 77.
What is the value of variable jsonObject?
 
Oh I think your problem is that you're not returning Json data. What's the value of 'response' parameter to your onResponse() method?
 
Run your app in debug mode and set a breakpoint at line 77.
What is the value of variable jsonObject?

<br />
<b>Notice</b>: Undefined index: Name in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: Surname in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>6</b><br />
<br />
<b>Notice</b>: Undefined index: Email in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>7</b><br />
<br />
<b>Notice</b>: Undefined index: Password in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>8</b><br />
<br />
<b>Warning</b>: mysqli_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES) in <b>C:\xampp\htdocs\android_register_login\connect.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: mysqli_query() expects parameter 1 to be mysqli, bool given in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>16</b><br />
<br />
<b>Notice</b>: Undefined variable: Result in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>28</b><br />
null<br />
<b>Warning</b>: mysqli_close() expects parameter 1 to be mysqli, bool given in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>29</b><br />
 
That's not JSON, it's HTML. And your PHP server has generated some warnings

Code:
<b>Notice</b>: Undefined variable: Result in <b>C:\xampp\htdocs\android_register_login\register.php</b> on line <b>28</b><br />
 
Start by looking at the errors generated by your PHP

Code:
Undefined index: Name

What does that tell you? It means that this statement

Code:
$Name = $_POST['Name'];

caused the error, because there was no 'Name' element in the _POST array. Why's that? Did you Java code fail to include the parameters on the HTTP request?

So then you turn your attention to the client side code. In particular this part:

Code:
            @Override
            protected Map<String, String> getParams() throws AuthFailureError{
                Map<String,String>params=new HashMap<>();
                params.put("Name", Name);
                params.put("Surname", Surname);
                params.put("Email", Email);
                params.put("Password", Password);
                return super.getParams();
            }

My first question would be, is this code getting executed? How do you determine that? Well you need to set a breakpoint in that part of the code, and run your app in debug mode. If you don't know how to do that learn. These are basic tools and knowledge you need, if you're doing Android development.

So you can see how your question isn't easy to answer, because there are multiple points of possible failure, and you need to start by doing some interactive debugging. This can't really be done on an Internet forum.
 
Threads merged and cleaned up.

Your basic problem is that your PHP code is generating errors.
As explained above, this could be because your Java code isn't sending correct parameters in the HTTP request. To investigate this further, you need to run the app in debug mode, set breakpoints in the code, and step through it. This is a basic technique you have to learn yourself, in order to be an effective developer.
Like I said previously, interactive debugging of code can not be done on a forum, you need to learn how to do this yourself.
If you have any further questions, after doing a bit of debugging, feel free to ask, but please be aware that this is an English speaking forum.
Thanks.
 
Back
Top Bottom