无法在AsyncTask的onPostExecute()方法中执行else语句

时间:2015-08-31 11:53:32

标签: android android-asynctask

public class LoginActivity extends Activity {

EditText uEmail, uPassword;
String emailID, password;
CheckBox chkRememberMe;
JSONObject jsonResponseObject, jsonObject, data;
String url = "";
String jsonResponseString = "";
String accessToken;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
String urlString = " http://192.168.2.17:8000/api/v1/login/?format=json";
Boolean error, success;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    uEmail = (EditText) findViewById(R.id.edtEmailId);
    uPassword = (EditText) findViewById(R.id.edtPassword);
    chkRememberMe = (CheckBox) findViewById(R.id.chkRememberMe);
    }


public void signUp(View v) {
    startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}

public void login(View v) {
    Log.e("Login", "clicked");
    emailID = uEmail.getText().toString().trim();
    password = uPassword.getText().toString().trim();
    new LoginTask().execute(emailID, password);

}

class LoginTask extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        StringBuilder sb = new StringBuilder();
        emailID = params[0];
        Log.e("email", emailID);
        password = params[1];
        Log.e("Password", password);
        // convert text data to JSON format
        jsonObject = new JSONObject();
        try {
            jsonObject.accumulate("email", emailID);
            jsonObject.accumulate("password", password);

        } catch (Exception ex) {
            Log.e("Parsing error", ex.toString());
        }

        //convert json data to String which have to send
        String jsonStringToPost = jsonObject.toString();
        Log.e("JSON String to post", jsonStringToPost);

        try {
            //sending data to API
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            //urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setReadTimeout(15000); //Sets the maximum time to wait for an input stream read to complete before giving up
            urlConnection.setConnectTimeout(15000); //Sets the maximum time in milliseconds to wait while connecting
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            out.write(jsonStringToPost);
            out.flush();
            out.close();
            //getting response
            InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String responseData = br.readLine();
            while (responseData != null) {
                sb.append(responseData);
                responseData = br.readLine();
            }
            br.close();
            urlConnection.disconnect();
        } catch (Exception ex) {
            Log.e("Connection error", ex.toString());
        }
        jsonResponseString = sb.toString();
        return jsonResponseString;
    }

    @Override
    protected void onPostExecute(String s) {
        jsonResponseString = s;
        Log.e("Response String", jsonResponseString);
        try {
            jsonResponseObject = new JSONObject(jsonResponseString);

            if (success = jsonResponseObject.getBoolean("success")) {
                Log.e("Success", String.valueOf(success));
            } else if(error = jsonResponseObject.getBoolean("error")) {
                Log.e("Error", String.valueOf(error));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
}

这是我的登录页面的代码。点击登录按钮后,系统会调用login()方法。我通过emailIdpassword格式向{}发送JSONAsyncTask。在onPostExecute()中,我使用从API收到的JSON响应字符串。我将获得success = true成功登录,error = true无效登录。

onPostExecute()方法中,我想使用if-else条件检查登录是成功还是失败,但即使提供无效emailID和{{{}后,我也无法执行其他部分1}}。我们不能在password方法中使用if-else吗?

成功登录时的JSON

onPostExecute()

登录失败的JSON

{ 
    "data": 
        { 
            "access_token": "2c1KjajSYDS6kJqzD1wJ1eGZTO2JbC", 
            "token_type": 
            "Bearer", 
            "expires_in": 36000, 
            "refresh_token": "HLYN8H38G2f9wR8doPxKBNDCZ7KFMg", 
            "scope": "read write groups" 
        }, 
    "success": true 
} 

2 个答案:

答案 0 :(得分:0)

我不确定,但也许if作业总是被评估为真,因为作业是合法的,因此你不会到达其他部分?

尝试使用:

@Override
protected void onPostExecute(String s) {
    jsonResponseString = s;
    Log.e("Response String", jsonResponseString);
    try {
        jsonResponseObject = new JSONObject(jsonResponseString);

        if (jsonResponseObject.getBoolean("success")) {
            success = jsonResponseObject.getBoolean("success");
            Log.e("Success", String.valueOf(success));
        } else if(jsonResponseObject.getBoolean("error")) {
            error = jsonResponseObject.getBoolean("error");
            Log.e("Error", String.valueOf(error));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

正如Karan Mer所说,你在那里放了错误的代码。 如果你必须比较,你应该使用&#34; ==&#34;,而不是赋值运算符&#34; =&#34;。 您还要将响应与&#34;成功&#34;进行比较。和&#34;错误&#34;布尔,但你还没有初始化它们,所以它们的价值总是假的。 更好的是你只需从响应中检查成功价值,这足够...... 用,替换你的代码,

if (jsonResponseObject.has("success")) {
    success = jsonResponseObject.getBoolean("success");
    Log.e("Success", String.valueOf(success));
} else if(jsonResponseObject.has("error")){
    error = jsonResponseObject.getBoolean("error");
    Log.e("Error", String.valueOf(error));
}

这将确保它是否具有布尔值&#34;成功&#34;然后只会检查它。理想情况下,在这种情况下,响应应该只有&#34;成功&#34;值为真或假,并且不需要&#34;错误&#34;布尔格了。