Android:即使连接成功,也无法存储或从数据库中获取

时间:2015-11-19 00:30:59

标签: java android httpconnection

我是第一次在Android编码,我正在开发一个登录页面。运行应用程序时没有错误,但即使我输入了正确的详细信息,应用程序也会向我显示“用户详细信息不正确”消息。在调试代码之后,我发现错误是在执行此行时。

OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

我设置了不同的断点,并发现一旦执行此行,我就会收到错误消息。

这是我的完整代码:

    public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
        User user;
        GetUserCallback userCallback;

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

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

            Map<String, String> dataToSend = new HashMap<>();

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

            String encodedStr = getEncodedData(dataToSend);

            BufferedReader reader = null;

            User returnedUser = null;

            try{
                //Converting the address string into URL
                URL url = new URL(SERVER_ADDRESS + "FetchUserData.php");

                //Opening the connection
                 HttpURLConnection con = (HttpURLConnection) url.openConnection();

                con.setRequestMethod("POST");
                con.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

                writer.write(encodedStr);
                writer.flush();

                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line;
                while((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                line = sb.toString();

                Log.i("custom check","The values received are:");
                Log.i("custom check",line);

                JSONObject jobject = new JSONObject(line);

                if(jobject.length() == 0){
                    returnedUser = null;
                }else{
                    String fname = jobject.getString("FirstName");
                    String lname = jobject.getString("LastName");

                    returnedUser = new User(fname, lname, user.username, user.password);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(reader != null) {
                    try{
                        reader.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }

            return returnedUser;
        }

问题是即使我输入了正确的凭据,“returnedUser”也始终为null,这就是显示错误消息的原因。

0 个答案:

没有答案