我试图从SQL数据库中获取数据,但我真的不知道什么是错的

时间:2015-12-02 18:19:18

标签: android android-asynctask

我试图从数据库中获取一些数据,但是我得到了“致命错误”.AsyncTask#2'。我真的很新java和android工作室,因此我不知道我做了什么是正确的方法去做它。但简而言之,这就是我试图从数据库中读取JsonObject的内容。:

设置inputput流(con.getInputStream) 将其转换为字符串 并将其发送到JSONobject进行读取然后返回。

我正在使用API​​ 23,而且我还没有真正发现很多/从网上可用的内容中了解多少。帮助将非常感谢。

public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {

    User user;
    GetUserCallback userCallback;

    fetchUserDataAsyncTask(User user, GetUserCallback userCallback) {
        this.user = user;
        this.userCallback = userCallback;
    }

    @Override
    protected User doInBackground(Void... params) {

        //Use HashMap, it works similar to NameValuePair
        Map<String, String> dataToSend = new HashMap<>();

        dataToSend.put("username", user.username);
        dataToSend.put("password", user.password);

        //Encoded String - we will have to encode string by our custom method (Very easy)
        String encodedStr = getEncodedData(dataToSend);


        User returneduser = null; //for the JSONobject

        try {

            //Converting address String to URL
            URL url = new URL(Server_Address + "FetchUserData.php");

            //Opening the connection (Not setting or using CONNECTION_TIMEOUT)
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            //Post Method
            con.setRequestMethod("POST");
            //To enable inputting values using POST method
            //(Basically, after this we can write the dataToSend to the body of POST method

            con.setDoOutput(true);

            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
            //Writing dataToSend to outputstreamwriter
            writer.write(encodedStr);
            //Sending the data to the server - This much is enough to send data to server
            //But to read the response of the server, you will have to implement the procedure below
            writer.flush();



            //Attempt to read data and shit but doesnt work
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line = null;

            while ((line = reader.readLine()) != null) { //Read till there is something available
                sb.append(line + "\n");     //Reading and saving line by line - not all at once
            }

            line = sb.toString();           //Saving complete data received in string, you can do it differently

            try {
                JSONObject jObject = new JSONObject(line);//result in the ().

                if (jObject.length() == 0) {
                    returneduser = null;
                }
                    else {

                        try {
                            String name = jObject.getString("name");
                            String teamname = jObject.getString("teamname");
                            String username = jObject.getString("username");
                            String password = jObject.getString("password");
                            String emailad = jObject.getString("emailad");

                            returneduser = new User(name, teamname, username, emailad, password);

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

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

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

        return returneduser;
    }

    @Override
    protected void onPostExecute(User returneduser) {
        progressDialog.dismiss();
        userCallback.done(returneduser);
        super.onPostExecute(returneduser);

    }

      //get encoded data (edit)

       (private String getEncodedData(Map<String, String> data) {
    StringBuilder sb = new StringBuilder();
    for (String key : data.keySet()) {
        String value = null;
        try {
            value = URLEncoder.encode(data.get(key), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (sb.length() > 0)
            sb.append("&");

        sb.append(key + "=" + value);
    }
    return sb.toString();
})

}

错误堆栈:

12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: Process: pk.com.gameon.myapplication, PID: 8414
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:309)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at libcore.net.UriCodec.encode(UriCodec.java:132)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.net.URLEncoder.encode(URLEncoder.java:57)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at pk.com.gameon.myapplication.ServerRequest.getEncodedData(ServerRequest.java:134)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at pk.com.gameon.myapplication.ServerRequest.access$000(ServerRequest.java:29)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at pk.com.gameon.myapplication.ServerRequest$fetchUserDataAsyncTask.doInBackground(ServerRequest.java:168)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at pk.com.gameon.myapplication.ServerRequest$fetchUserDataAsyncTask.doInBackground(ServerRequest.java:148)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)     
12-02 23:36:23.546 8414-8443/pk.com.gameon.myapplication E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818) 
12-02 23:36:24.617 8414-8441/pk.com.gameon.myapplication E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab753b90
12-02 23:36:25.453 8414-8441/pk.com.gameon.myapplication E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab755100

1 个答案:

答案 0 :(得分:1)

这是你的罪魁祸首:

java.lang.NullPointerException: Attempt to invoke virtual method 'int 
java.lang.String.length()' on a null object reference

你在AsyncTask中调用它:

if (jObject.length() == 0) {
    returneduser = null;
}

相反,请将其更改为:

if(jObject == null || jObject.length() == 0) {
    returneduser = null;
}

这样在检查时它是空的。此外,您可以通过在代码中设置断点并通过Android Studio或Intellij或Eclipse运行调试器来验证这一点,具体取决于您使用的是什么。这是您最好的选择,我建议您尝试使用这些无法轻易识别的错误。在大多数情况下,您将快速看到错误,并可以查看断点范围内所有变量的值,以验证它们是否符合预期。

另一种效率较低的方法是在任何地方删除Log.i(String,String)行以跟踪发生的情况以及应用程序的状态,然后将其转换为log cat输出。