2

So first of all, im new to this kind of stuff. I got an app with registration activity. Everything works fine except messages after successful/unsuccessful try. Android studio gives me

JSONException: Value of type java.lang.String cannot be converted to JSONObject

and I have completely no idea how to fix that. Anyone here that could help at least a bit? Thanks!

package info.logirej.activity;

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 org.json.JSONException;
import org.json.JSONObject;

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

import info.logirej.R;
import info.logirej.app.AppConfig;
import info.logirej.app.AppController;
import info.logirej.helper.SQLiteHandler;
import info.logirej.helper.SessionManager;

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

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

        inputImie = (EditText) findViewById(R.id.imie);
        inputNazwisko = (EditText) findViewById(R.id.nazwisko);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        inputPin = (EditText) findViewById(R.id.pin);
        inputTelefon = (EditText) findViewById(R.id.telefon);
        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 imie = inputImie.getText().toString().trim();
                String nazwisko = inputNazwisko.getText().toString().trim();
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();
                String pin = inputPin.getText().toString().trim();
                String telefon = inputTelefon.getText().toString().trim();

                if (!imie.isEmpty() && !nazwisko.isEmpty() && !email.isEmpty() && !password.isEmpty() && !pin.isEmpty() && !telefon.isEmpty()) {
                    registerUser(imie, nazwisko, email, password, pin, telefon);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Prosze wprowadzić dane!", 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 imie, final String nazwisko, final String email, final String pin, final String telefon,
                              final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Tworzę konto");
        showDialog();

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

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Stan rejestracji: " + response.toString());
                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 imie = user.getString("imie");
                        String nazwisko = user.getString("nazwisko");
                        String email = user.getString("email");
                        String pin = user.getString("pin");
                        String telefon = user.getString("telefon");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(imie, nazwisko, email, pin, telefon, uid, created_at);

                        Toast.makeText(getApplicationContext(), "Konto zostało utworzone! Zapraszamy do logowania!", Toast.LENGTH_LONG).show();

                        // 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, "Błąd rejestracji: " + 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("imie", imie);
                params.put("nazwisko", nazwisko);
                params.put("email", email);
                params.put("password", password);
                params.put("pin", pin);
                params.put("telefon", telefon);

                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();
    }
}
  • post the result of this log: Log.d(TAG, "Stan rejestracji: " + response.toString()); If response is not in json format, it will throw an exception. – Paulo Oct 20 '16 at 22:05
  • It would appear that `response` does not contain the JSON data you think it does. My guess is that error comes from `jObj.getJSONObject("user")`, which means that the `user` field on the response is a JSON string literal, not a JSON object. Perhaps if you **debug** your code and examine the value of `response`, things would be clearer for you. – Andreas Oct 20 '16 at 22:14
  • @Paulo Unfortunateely I have no idea how to get those logs. Could you maybe direct me somehow how to? – Shayenowsky Op Oct 20 '16 at 22:19
  • @Andreas Trying to debug that activity: Error running RegisterActivity: The activity must be exported or contain an intent-filter – Shayenowsky Op Oct 20 '16 at 22:20
  • plz provide your json response – jigar savaliya Jul 31 '17 at 09:05

1 Answers1

0

Your problem in the following line:

JSONObject jObj = new JSONObject(response);

Obviously, your response is invalid JSON, since I can not see how it is built, can't tell you much more.

Try to validate your JSON response here http://jsonlint.com/#

Alex Kamenkov
  • 891
  • 1
  • 6
  • 16
  • I can share anything that is needed but since i've never made any, and I have no idea what is JSON response, I would need some deeper help. Google is not helping me unfortunateely – Shayenowsky Op Oct 21 '16 at 00:13
  • Android - JSON Parser Tutorial https://www.tutorialspoint.com/android/android_json_parser.htm – Alex Kamenkov Oct 21 '16 at 00:52