导致java.lang.RuntimeException的JSONObject getInt(string)方法。 Android Studio

时间:2016-07-21 20:06:41

标签: java php android json database-server

我正在尝试检查用户是否输入了正确的用户ID和密码以登录该应用。我的数据库已经在线部署。一切顺利,直到我得到结果,以检查是否允许用户继续。但问题是我没有得到任何结果。相反,我在JSONObject的getInt(String)方法上得到了一个java.lang.RuntimeException。这是我的LoginActivity.java

public class LoginActivity extends AppCompatActivity {

    JSONParser jsonParser = new JSONParser();
    // single product url
    private static final String url_user_check_login = "####/android_connect/check_user_login.php?username=#### & password=#####";
     int success=0;
    String id="";
    String password="";
    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

//        Defining onClickListener for Login Button
        Button loginBtn=(Button) findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Check credentials
                EditText phone=(EditText)findViewById(R.id.phone_txt);
                EditText pwd=(EditText)findViewById(R.id.password_txt);
                id=phone.getText().toString();
                password=pwd.getText().toString();
                new CheckUserLogin().execute();

            }
        });
    }

    class CheckUserLogin extends AsyncTask<String, String, String> {

        protected String doInBackground(String... params) {


                    // Check for success tag

                    try {
                        // Building Parameters
                        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                        params1.add(new BasicNameValuePair("id", id));
                        params1.add(new BasicNameValuePair("password", password));

                        JSONObject json = jsonParser.makeHttpRequest(
                                url_user_check_login, "GET", params1);


                        // json success tag
                        success = json.getInt(TAG_SUCCESS);//This is the line where i am getting the exception

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                }
//            });

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            if (success == 1) {

                Intent intent=new Intent(getApplicationContext(), RideDetailsActivity.class);
                startActivity(intent);

            }
        }
    }
}

这是我正在使用的php文件。

db_connect.php

db_connect.php
<?php

/**
 * A class file to connect to database
 */
class DB_CONNECT {

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }

    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

        // returing connection cursor
        return $con;
    }

    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }

}

?>

db_config.php

db_config.php
<?php

/*
 * All database connection variables
 */

define('DB_USER', "####"); // db user
define('DB_PASSWORD', "####"); // db password (mention your db password here)
define('DB_DATABASE', "####"); // database name
define('DB_SERVER', "###.###.###); // db server
?>

check_user_login.php

check_user_login.php
<?php

/*
 * Following code will check user credentials for log in
 * uid and password are used to check if the user has permission to log in
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["id"]) && isset($_GET["password"])) {
    $id = $_GET['id'];
    $password = $_GET['password'];

    // get a product from products table
    $result = mysql_query("SELECT * FROM tb_login WHERE id = $id AND password = $password");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            // success
            $response["success"] = 1;
            $response["message"] = "User found";

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no user found
            $response["success"] = 0;
            $response["message"] = "No user found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no user found
        $response["success"] = 0;
        $response["message"] = "No user found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

以下是异常的堆栈跟踪

FATAL EXCEPTION: AsyncTask #4
                                                                   java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.NullPointerException
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:100)
at com.heycabs.heycabs.LoginActivity$CheckUserLogin.doInBackground(LoginActivity.java:59)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
at java.lang.Thread.run(Thread.java:838) 

另外我不知道所以我要问我是否必须提及数据库的端口号以及数据库服务器的IP地址?我是php的新手,在android中使用JSON。因此,在指出任何明显错误时请务必考虑周到。感谢。

1 个答案:

答案 0 :(得分:0)

查看此页面。 http://danielnugent.blogspot.com/2015/06/updated-jsonparser-with.html 根据您在评论中发布的教程,您使用的JSONParser似乎是问题所在。

以下是更新JSONParser的代码,如果您只想尝试将其插入代码并查看它是否能解决您的问题。如果您想阅读更多内容,请单击链接。

   import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}