Home » Php » php – Java: Error “java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $”

php – Java: Error “java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $”

Posted by: admin February 25, 2020 Leave a comment


I am trying to post user information to MYSQL database by Retrofit2. I am taking the information by edittexts, then passing them as a User object by retrofit. My server-side codes are written by php which is working nicely independently. I have checked it by postman. Why am I getting this error?


EditText editTextFullName, editTextUsername, editTextPassword, editTextEmail, editTextCollege, editTextDOB;
    RadioGroup radioGroupGender;
    Button btnRegister, btnCancel;
    QuizDbHelper db;

    Gson gson = new GsonBuilder()

    Retrofit retrofit = new Retrofit.Builder()
    UsersAPI usersAPI = retrofit.create(UsersAPI.class);

    protected void onCreate(Bundle savedInstanceState) {
        editTextCollege = findViewById(R.id.editTextCollege);
        editTextDOB = findViewById(R.id.editTextDateOfBirth);
        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword = findViewById(R.id.editTextPassword);
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextFullName = findViewById(R.id.editTextFullName);
        radioGroupGender = findViewById(R.id.radioGroupGender);
        btnCancel = findViewById(R.id.btnCancel);
        btnRegister = findViewById(R.id.btnRegister);
        db = new QuizDbHelper(this);

        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //Get data from input
                String usernameValue = editTextUsername.getText().toString();
                String passwordValue = editTextPassword.getText().toString();
                String emailValue = editTextEmail.getText().toString();
                String DOBValue = editTextDOB.getText().toString();
                String collegeValue = editTextCollege.getText().toString();
                String fullnameValue = editTextFullName.getText().toString();
                RadioButton genderChecked = findViewById(radioGroupGender.getCheckedRadioButtonId());
                String genderValue = genderChecked.getText().toString();
                User user = new User(fullnameValue,usernameValue,collegeValue,DOBValue,emailValue,genderValue,passwordValue);

                //push to remote database
                Call<User> call= usersAPI.createUser(user);
                call.enqueue(new Callback<User>() {
                    public void onResponse(Call<User> call, Response<User> response) {
                            Toast.makeText(Register.this, "Code: "+ response.code(), Toast.LENGTH_SHORT).show();

                        StringBuffer buffer = new StringBuffer();
                        User postResponse = response.body();
                        buffer.append("Id : " + postResponse.getId() + "\n");
                        buffer.append("User Name : " + postResponse.getUserName() + "\n");
                        buffer.append("Email:  " + postResponse.getEmail() + "\n");
                        buffer.append("Fullname:  " + postResponse.getEmail() + "\n");
                        buffer.append("College:  " + postResponse.getCollegeName() + "\n");
                        buffer.append("Gender:  " + postResponse.getGender() + "\n");
                        buffer.append("DOB:  " + postResponse.getDob() + "\n\n");
                        AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                        builder.setTitle("User Created");


                    public void onFailure(Call<User> call, Throwable t) {

      //I am getting error here. in the app as a Toast.
    Toast.makeText(Register.this, "Error Failed : "+ t.getMessage(), 


import java.util.List;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface UsersAPI {

    Call<List<User>> getUsers();

   /* @DELETE("delete_user.php?id={id}")
    Call<Void> deletePost(@Path("id") int id);*/

    Call<Void> deletePost(@Query("id") int id);

    Call<User> createUser(@Body User user);

Here is my PHP code


    require "init.php";
    $user_name = $_POST["userName"];
    $password = md5($_POST["password"]);
    $email = $_POST["email"];
    $fullname = $_POST["fullName"];
    $college = $_POST["collegeName"];
    $gender = $_POST["gender"];
    $dob = $_POST["dob"];

    //echo $password;

    $sql = "select * from users where Username = '$user_name'";

    $result = mysqli_query($con,$sql);
    // checking if username exists or not
    if (mysqli_num_rows($result)>0){
        $status = "exists";
        //echo "The username exists";
        $sql = "insert into users (Username, Password, Email, Fullname, College, Gender, DOB) values('$user_name','$password','$email','$fullname','$college','$gender','$dob');";
            $status = "Registration Success";
            //echo $status;
            $status = "Resgistration Failed";
            //echo $status;
    echo json_encode(array("response" => $status));


And here is my User class:

    public class User {

    private int id;
    private String fullName;
    private String userName;
    private String collegeName;
    private String dob;
    private String email;
    private String mobileNo;
    private String gender;
    private String password;

    public User() {

    public User(String fullName, String userName, String collegeName, String dob, String email, String gender, String password) {
        this.fullName = fullName;
        this.userName = userName;
        this.collegeName = collegeName;
        this.dob = dob;
        this.email = email;
        this.gender = gender;
        this.password = password;

    public String getGender() {
        return gender;

    public void setGender(String gender) {
        this.gender = gender;

    public int getId() {
        return id;

    public void setId(int id) {
        this.id = id;

    public String getFullName() {
        return fullName;

    public void setFullName(String fullName) {
        this.fullName = fullName;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

    public String getCollegeName() {
        return collegeName;

    public void setCollegeName(String collegeName) {
        this.collegeName = collegeName;

    public String getDob() {
        return dob;

    public void setDob(String dob) {
        this.dob = dob;

    public String getEmail() {
        return email;

    public void setEmail(String email) {
        this.email = email;

    public String getMobileNo() {
        return mobileNo;

    public void setMobileNo(String mobileNo) {
        this.mobileNo = mobileNo;

How to&Answers:


You’re apparently getting a toast with the error message java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $”


All we know, from what you’ve told us so far, is:

  1. Since it’s a toast, it’s coming from Android.

  2. The error message java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING... implies that the error is occurring trying to parse an illegal JSON string.


  1. Ideally, you’d have some stack traceback. It appears that you don’t 🙁 So then…

  2. Step through your code in the debugger (Android Studio?), try to find the line preceding the toast. See if you can “step into” the method that encountered the error.

  3. In parallel, try to enable “verbose logging”. For example:

    Logging in Retrofit2

  4. The most important thing you can do – short of finding a stack traceback – is to find the offending JSON.

    You might be able to see it in the debugger (step 4), or in the verbose log (step 5).

    Heck, you might even see it if you set a breakpoint in your onResponse() method and looked at the response object!


Let’s say you get an HTTP error from the server. Instead of responding with a JSON object, the server might instead return some HTML text (for example, the error message formatted as HTML).

But we need to learn more. The code you posted for “Register.php” and “User Class” is completely unhelpful 🙁

Please post back what you find.