如何修复:org.json.JSONException:java.lang.String类型的值无法转换为JSONObject

时间:2016-10-20 21:57:45

标签: java android json

首先,我对这种东西不熟悉。我有一个注册活动的应用程序。除了成功/不成功尝试后的消息,一切正常。 Android工作室给了我

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

我完全不知道如何解决这个问题。这里的任何人至少可以帮助一下吗?谢谢!

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();
    }
}

1 个答案:

答案 0 :(得分:0)

您的问题在以下一行:

JSONObject jObj = new JSONObject(response);

显然,您的回复是无效的JSON,因为我无法看到它是如何构建的,不能告诉您更多。

尝试在此处验证您的JSON响应 http://jsonlint.com/#