java - 为什么无法在AsyncTask中使用if / else?

时间:2016-07-14 12:26:15

标签: java android

我正在尝试显示提交的数据的消息,并且用户存在于onPostExecute()方法中,但它没有正确显示消息给我建议 当我运行应用程序时,它显示来自onPost方法的捕获消息我希望通过操作显示特定消息

    //java file

    public class SignupActivity extends AsyncTask<String, Void, String> {

        private Context context;

        public SignupActivity(Context context) {
            this.context = context;
        }

        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(String... arg0) {
            String fullName = arg0[0];
          //  String userName = arg0[1];
            String passWord = arg0[1];
            String phoneNumber = arg0[2];
            String emailAddress = arg0[3];

            String link;
            String data;
            BufferedReader bufferedReader;
            String result;

            try {
                data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
            //    data += "&username=" + URLEncoder.encode(userName, "UTF-8");
                data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
                data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
                data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");


              link = "http://... .php" + data;

                URL url = new URL(link);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();

                bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                result = bufferedReader.readLine();
                return result;
            } catch (Exception e) {
                return new String("Exception: " + e.getMessage());
            }
        }

        @Override
        protected void onPostExecute(String result) {
            String jsonStr = result;

            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                String query_result = jsonObj.getString("query_result");
                if (query_result.equals("SUCCESS")) {
                    Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();

                }
                else{
                    Toast.makeText(context, "Exist Already.", Toast.LENGTH_SHORT).show();
                }

                /*       else if (query_result.equals("FAILURE")) {
                        Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
                    }  */
            } catch (JSONException e) {
                e.printStackTrace();
                // Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
                // Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
                Toast.makeText(context, "Please Login", Toast.LENGTH_SHORT).show();

            }

        /*    if (jsonStr == null) {
                Toast.makeText(context, "cond1", Toast.LENGTH_SHORT).show();
            }

            else if(jsonStr != null)
            {

                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    String query_result = jsonObj.getString("query_result");
                    if (query_result.equals("SUCCESS")) {
                        Toast.makeText(context, "Data inserted successfully. Signup successfull.", Toast.LENGTH_LONG).show();

                    }

                    //    else if (query_result.equals("FAILURE")) {
                    //       Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
                    //    }
                    else{
                        Toast.makeText(context, "Exists", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    // Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
                    Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();

                }
            }
            else{
                Toast.makeText(context, "cond2", Toast.LENGTH_SHORT).show();
            }
        */

        /*    if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    String query_result = jsonObj.getString("query_result");
                    if (query_result.equals("SUCCESS")) {
                        Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();

                    }

                     else if (query_result.equals("FAILURE")) {
                        Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                   // Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
                   // Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
                    Toast.makeText(context, "Please Login", Toast.LENGTH_SHORT).show();

                }
            } else {
                Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
            }  */
        }
    }

PHP代码

<?php

$mysql = new mysqli('localhost', 'user', 'pass', 'db');    

/* If an error code is reported... */
if($mysql->connect_errno)
{
  echo json_encode(array(
    'query_result' => 'ERROR'
  ));
}
/* Otherwise go ahead... */
else
{
  /* Prepare a select statement to check user existence */
  $selectStmt = $mysql->prepare("SELECT * FROM `users10` WHERE `phone` = ? OR `email` = ?");

  /* Retrieve arguments */
  $fullName = $_GET['fullname'];
  //$userName = $_GET['username'];
  $passWord = $_GET['password'];
  $phoneNumber = $_GET['phonenumber'];
  $emailAddress = $_GET['emailaddress'];

  /* Binding parameters */
  $selectStmt->bind_param('ss', $phoneNumber, $emailAddress);

  /* Execute statement */
  if (!$selectStmt->execute()) {
    echo json_encode(array(
      'query_result' => 'ERROR'
    ));
  }
  else
  {
    /* If the number of returned rows is 0 */
    if(0 === $selectStmt->get_result()->num_rows)
    {
      $insertStmt = $mysql->prepare("INSERT INTO `users10` (`fullname`, `password`, `phone`, `email`) VALUES (?, ?, ?, ?)");
      $insertStmt->bind_param('ssss', $fullName, $passWord, $phoneNumber, $emailAddress);

      /* Try to insert the new user */
      if (!$insertStmt->execute()) {
        echo json_encode(array(
          'query_result' => 'FAILURE'
        ));
      }
      else
      {
        echo json_encode(array(
          'query_result' => 'SUCCESS'
        ));
      }
    }
    else
    {
      echo json_encode(array(
        'query_result' => 'FAILURE'
      ));
    }
  }
}
?>

1 个答案:

答案 0 :(得分:0)

我认为您的jsonStr存在问题,您应该替换此行

return new String("Exception: " + e.getMessage());

return null;

在你的onpostexecute中这样做

            @Override
    protected void onPostExecute(String result) {
       String jsonStr = result;



        try {

        Log.d("jsonStr","jsonStr="+jsonStr); // to check in logcat you have a valid json string

         if(!TextUtils.isEmpty(jsonStr)){  // to be sure jsonStr is not null and not empty

            JSONObject jsonObj = new JSONObject(jsonStr.trim());
            String query_result = jsonObj.getString("query_result");
            if (query_result.equalIgnoreCase("SUCCESS")) {
                Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();

            }
            else{
                Toast.makeText(context, "Exist Already.", Toast.LENGTH_SHORT).show();
            }
         else{
                Toast.makeText(context, "your jsonStr is empty or null", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
            //JSONObject jsonObj = new JSONObject(jsonStr); Exception at this line
            Toast.makeText(context, "you have a bad json string", Toast.LENGTH_SHORT).show();

        }


    }

希望它可以帮到你