简体   繁体   English

Android:如何将Java.String转换为JSONObject

[英]Android : How to Convert a Java.String into a JSONObject

I've just started coding using Android Studio and i stumbled into a problem I cant find a solution for. 我刚刚开始使用Android Studio进行编码,但遇到一个我找不到解决方案的问题。 I tried creating a Login/Register Activities and while the Register is working perfect the Login is giving me a hard time with the next error : 我尝试创建一个登录/注册活动,并且在注册器正常运行时,登录使我很难解决下一个错误:

"Json error :Value<br><table of type java.lang.String cannot be converted to JSONObject"

while debugging I managed to find the source of the problem and ill paste the code here : 在调试时,我设法找到问题的根源,并将代码粘贴在这里:

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

    };

The debugger points me to the line that is marked with ** ... **. 调试器将我指向标有** ... **的行。

if anyone can help me figure the solution for this I would appreciate it. 如果有人可以帮助我找到解决方案,我将不胜感激。 (if more code is needed or anything like that just let me know and ill add it). (如果需要更多代码或类似的代码,请告诉我,然后加上)。

btw i'm using 000webhost which have a MYSQL ver. 顺便说一句,我正在使用具有MYSQL版本的000webhost。 5.1. 5.1。 database connection is good and its working (tested on registration and it works great). 数据库连接良好并且可以正常工作(经过注册测试,效果很好)。

the errors I get on DDMS, 我在DDMS上遇到的错误,

    11-29 17:42:04.036: D/RegisterActivity(2188): Login Response: <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><font face='Arial' size='1' color='#000000'><b>PHP Error Message</b></font></td></tr></table><br />
11-29 17:42:04.036: D/RegisterActivity(2188): <b>Fatal error</b>:  Call to undefined method mysqli_stmt::get_result() in <b>/home/a4085630/public_html/include/DB_Functions.php</b> on line <b>59</b><br />
11-29 17:42:04.036: D/RegisterActivity(2188): <br><table border='1' cellpadding='2' bgcolor='#FFFFDF' bordercolor='#E8B900' align='center'><tr><td><div align='center'><a href='http://www.000webhost.com/'><font face='Arial' size='1' color='#000000'>Free Web Hosting</font></a></div></td></tr></table>
11-29 17:42:04.059: E/Surface(2188): getSlotFromBufferLocked: unknown buffer: 0xb3f967c0
11-29 17:42:04.065: W/System.err(2188): org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
11-29 17:42:04.065: W/System.err(2188):     at org.json.JSON.typeMismatch(JSON.java:111)
11-29 17:42:04.065: W/System.err(2188):     at org.json.JSONObject.<init>(JSONObject.java:160)
11-29 17:42:04.065: W/System.err(2188):     at org.json.JSONObject.<init>(JSONObject.java:173)
11-29 17:42:04.065: W/System.err(2188):     at markitcommunity.org.markit.activity.LoginActivity$3.onResponse(LoginActivity.java:123)
11-29 17:42:04.065: W/System.err(2188):     at markitcommunity.org.markit.activity.LoginActivity$3.onResponse(LoginActivity.java:114)
11-29 17:42:04.065: W/System.err(2188):     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
11-29 17:42:04.065: W/System.err(2188):     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
11-29 17:42:04.065: W/System.err(2188):     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
11-29 17:42:04.065: W/System.err(2188):     at android.os.Handler.handleCallback(Handler.java:739)
11-29 17:42:04.065: W/System.err(2188):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-29 17:42:04.065: W/System.err(2188):     at android.os.Looper.loop(Looper.java:148)
11-29 17:42:04.065: W/System.err(2188):     at android.app.ActivityThread.main(ActivityThread.java:5417)
11-29 17:42:04.065: W/System.err(2188):     at java.lang.reflect.Method.invoke(Native Method)
11-29 17:42:04.066: W/System.err(2188):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-29 17:42:04.066: W/System.err(2188):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-29 17:42:04.114: W/EGL_emulation(2188): eglSurfaceAttrib not implemented
11-29 17:42:04.114: W/OpenGLRenderer(2188): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa2dc7a20, error=EGL_SUCCESS

DB_Functions.PHP Code -- DB_Functions.PHP代码-

<?php

class DB_Functions {

    private $conn;

    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $db = new Db_Connect();
        $this->conn = $db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt

        $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
        $result = $stmt->execute();
        $stmt->close();

        // check for successful store
        if ($result) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            return $user;
        } else {
            return false;
        }
    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($email, $password) {

        $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");

        $stmt->bind_param("s", $email);

        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            return $user;
        } else {
            return NULL;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");

        $stmt->bind_param("s", $email);

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // user existed 
            $stmt->close();
            return true;
        } else {
            // user not existed
            $stmt->close();
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>

after a very long research pretty much everywhere and changing my host i realised that this specific line is what give the error : 经过几乎所有地方的长时间研究并更改了主机,我意识到此特定行是导致错误的原因:

$user = $stmt->get_result()->fetch_assoc();

as it fetch the HTML build of the table instead of its content into the user. 因为它获取表的HTML版本,而不是其内容输入用户。

anyone have any idea on how to solve this please? 有人对如何解决这个问题有任何想法吗?

well after a very long research it seems that my web hosting doesnt support mysqlnd driver therefor i changed the code to the following and it solved the problem. 经过长时间的研究,我的网络托管似乎不支持mysqlnd驱动程序,因此我将代码更改为以下代码,从而解决了该问题。

/**
 * Get user by email and password
 */
public function getUserByEmailAndPassword($email, $password) {

    $stmt = $this->conn->prepare("SELECT unique_id,name,email,created_at,updated_at, encrypted_password , salt FROM users WHERE email = ?");

    $stmt->bind_param("s", $email);

    if ($stmt->execute()) {
            $stmt->store_result();
            $num_of_rows = $stmt->num_rows;
            $stmt->bind_result($aid, $aname, $aemail, $acreated_at, $aupdated_at , $aencrypted_password , $asalt);

                    while ($stmt->fetch()) {
                    $user[0] = $aid;
                    $user[1] = $aname;
                    $user[2] = $aemail;
                    $user[3] = $acreated_at;
                    $user[4] = $aupdated_at;
                    $user[5] = $aencrypted_password;
                    $user[6] = $asalt;
                    $user[7] = $this->checkhashSSHA($asalt, $password);
                    }
            $stmt->free_result();
            $stmt->close();
            return $user;
            } else {
            return NULL;
            }
    }

which pretty much collect the data from the SQL 1 column at a time, abit none dynamic but it works. 它几乎一次从SQL 1列中收集数据,虽然没有动态变化,但是可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM