!DOCTYPE of type java.lang.String cannot be converted to JSONObject

2.5k views Asked by At

I'm creating a user login and registration application with Android Studio but I'm a beginner and getting a JSONException.

I used this tutorial to put together my code.

Here's the error information:

06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:159)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:172)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at com.example.dev5.registration.app.RegisterActivity$3.onResponse(RegisterActivity.java:119)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at com.example.dev5.registration.app.RegisterActivity$3.onResponse(RegisterActivity.java:110)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5001)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-12 05:17:31.052    8831-8831/com.example.dev5.registration W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

And here's my code:

package com.example.dev5.registration.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.dev5.registration.app.helper.SQLiteHandler;
import com.example.dev5.registration.app.helper.SessionManager;

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

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

public class RegisterActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnRegister;
    private Button btnLinkToLogin;
    private EditText inputFullName;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

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

        inputFullName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this,
                MainActivity.class);
        startActivity(intent);
        finish();
    }

    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerUser(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}

/**
 * Function to store user in MySQL database will post params(tag, name,
 * email, password) to register url
 * */
private void registerUser(final String name, final String email,
                          final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";

    pDialog.setMessage("Registering ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            Log.d(TAG, "Register Response: " + response);
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {
                    // User successfully stored in MySQL
                    // Now store the user in sqlite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

                    // Launch login activity
                    Intent intent = new Intent(
                            RegisterActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {

                    // Error occurred in registration. Get the error
                    // message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Registration Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "register");
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}
}

Can anyone help explain it?

1

There are 1 answers

0
Amsheer On BEST ANSWER
"<!DOCTYPE of type java.lang.String cannot be converted to JSONObject"

This error happens for multiple reasons. One example is here. If suppose the server returns the error Page not found - 404. Then there is a HTML page. So your json not able to parse it.

The solution is you need to check your response returns from the server.

Edit 1:

You need to check your response before you parse your json there is one tool called POSTMAN try this.