Android,String无法转换为JSONObject

标签 android mysql string json

我想通过 Web 服务访问 Android 应用程序。 在 Web 服务中执行新注册。 在 Android 应用程序中,创建新注册的 xml 文件。 数据已成功保存在 SQL Server 数据库中,并且通过 Web 服务正确保存并以 jason 字符串返回数据。

但是当字符串转换为 JSONObject 时,它会给我这样的错误:

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

登录 Activity

package com.example.shy.wel.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 com.example.shy.wel.LoadingActivity;
import com.example.shy.wel.MainActivity;
import com.example.shy.wel.R;
import com.example.shy.wel.app.AppConfig;
import com.example.shy.wel.app.AppController;
import com.example.shy.wel.helper.SQLiteHandler;
import com.example.shy.wel.helper.SessionManager;

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

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

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    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_login);

        Intent loading = new Intent(this, LoadingActivity.class);
        startActivity(loading);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

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

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

        // Session manager
        session = new SessionManager(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(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

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

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

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


            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // 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 main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

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

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                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();
    }
}

我的logcat

04-22 13:41:55.092 14473-14521/com.example.shy.wel E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7facc84b6ad0
04-22 13:41:55.117 14473-14473/com.example.shy.wel W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
04-22 13:41:55.117 14473-14473/com.example.shy.wel W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
04-22 13:41:55.117 14473-14473/com.example.shy.wel W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
04-22 13:41:55.118 14473-14473/com.example.shy.wel W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
04-22 13:41:55.118 14473-14473/com.example.shy.wel W/System.err:     at com.example.shy.wel.activity.LoginActivity$3.onResponse(LoginActivity.java:129)
04-22 13:41:55.118 14473-14473/com.example.shy.wel W/System.err:     at com.example.shy.wel.activity.LoginActivity$3.onResponse(LoginActivity.java:120)
04-22 13:41:55.118 14473-14473/com.example.shy.wel W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
04-22 13:41:55.118 14473-14473/com.example.shy.wel W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
04-22 13:41:55.118 14473-14473/com.example.shy.wel W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
04-22 13:41:55.119 14473-14473/com.example.shy.wel W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-22 13:41:55.119 14473-14473/com.example.shy.wel W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-22 13:41:55.119 14473-14473/com.example.shy.wel W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-22 13:41:55.119 14473-14473/com.example.shy.wel W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-22 13:41:55.119 14473-14473/com.example.shy.wel W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-22 13:41:55.119 14473-14473/com.example.shy.wel W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-22 13:41:55.119 14473-14473/com.example.shy.wel W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-22 13:41:55.123 1606-1779/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@b10ec75 attribute=null, token = android.os.BinderProxy@afd2b1e
04-22 13:41:55.174 14473-14521/com.example.shy.wel W/EGL_emulation: eglSurfaceAttrib not implemented
04-22 13:41:55.174 14473-14521/com.example.shy.wel W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7facbe4a2500, error=EGL_SUCCESS
04-22 13:41:58.629 14473-14521/com.example.shy.wel E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7facc84b6c90

最佳答案

代码看起来不错。问题可能出在 JSON 中。尝试此页面 JSON Formatter and Validator 上生成的 JSON .

祝你好运!

关于Android,String无法转换为JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799891/

相关文章:

PHP/MySQL OnClick 更新 MySQL

android - 使用游标获取列内容

php - 我可以将 heroku 连接到外部 MySQL 服务器吗?

java - 从 Android 上捕获的异常生成解析崩溃报告

php - 如何最好地从带有 php 和 mysql 的分数表中获取某人的 'rank' 而无需循环

python - 将字符串添加到字符串变量python

python - 将数字格式化为字符串

c++ - 反转字符串的递归方法

android - 导致手机发热的应用

javascript - undefined 不是一个 native react 对象