为什么我的变量在成功方法之后初始化

时间:2016-04-18 08:08:01

标签: android android-asynctask retrofit

我正在尝试开发基于身份验证的基于web服务的身份验证Rest,我使用库Retrofit和async任务作为内部类。

如果用户存在,我有一个名为loginstatus的变量返回true,否则返回false。

问题是当编译器退出成功方法时,loginstatus初始化为false。

这是我的活动代码:

public class CheckLoginActivity extends Activity {

static AlertDialog dialog;
Button b;
UserModel userModel;
TextView statusTV;
EditText userNameET, passWordET;
String editTextUsername;
boolean loginStatus;
String editTextPassword;
String API_URL = "http://192.168.42.60/task_manager/v1/index.php";
SharedPreferences sharedpreferences;
public static final String USERPREFERENCE = "userPreference";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_check_login);
    final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
    final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
    usernameWrapper.setHint("Username");
    passwordWrapper.setHint("Password");
    dialog = new SpotsDialog(this, "Chargement");
    //NameText  control
    userNameET = (EditText) findViewById(R.id.editText1);
    passWordET = (EditText) findViewById(R.id.editText2);
    //Display Text control
    statusTV = (TextView) findViewById(R.id.tv_result);
    //Button to trigger web service invocation
    b = (Button) findViewById(R.id.button1);
    //Display progress bar until web service invocation completes
    //Button Click Listener
    sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Check if text controls are not empty
            if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
                if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") {
                    editTextUsername = userNameET.getText().toString();
                    editTextPassword = passWordET.getText().toString();
                    //        statusTV.setText("");
                    //Create instance for AsyncCallWS
                    AsyncCallWS task = new AsyncCallWS();

                    //Call execute
                    task.execute(editTextUsername, editTextPassword);
                }
                //If Password text control is empty
                else {
                         statusTV.setText("Please enter Password");
                }
                //If Username text control is empty
            } else {
                     statusTV.setText("Please enter Username");
            }
        }
    });
}

和我的异步任务

 private class AsyncCallWS extends AsyncTask<String, String, Void> {
    //Make Progress Bar visible
    protected void onPreExecute() {

        dialog.show();
    }

    @Override
    protected Void doInBackground(String... params) {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL)
                .build();
        geolocateApi post = restAdapter.create(geolocateApi.class);

        post.login(editTextUsername, editTextPassword, new Callback<UserModel>() {
            @Override
            public void success(UserModel userModelRecv, Response response) {
                if (userModelRecv != null) {
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString("username", userModelRecv.getUsername());
                    editor.putString("id", userModelRecv.getUser_id());
                    editor.putString("firstName", userModelRecv.getFirstName());
                    editor.putString("lastName", userModelRecv.getLastName());
                    editor.putString("Role", userModelRecv.getRole());
                    userModel=userModelRecv;
                    editor.commit();
                    loginStatus=true;
                }else  loginStatus=false;
            }

            @Override
            public void failure(RetrofitError error) {

            }

        });

        return null;
    }

    @Override
    //Once WebService returns response
    protected void onPostExecute(Void result) {
        //Make Progress Bar invisible

        Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class);
        try {
            Thread.sleep(200);
        } catch (Exception e) {
            e.printStackTrace();
        }
        dialog.hide();
        //Error status is false
            if (loginStatus) {
                //Based on Boolean value returned from WebService
                //Navigate to Home Screen
                startActivity(intSucces);
            } else {

                //Set Error message
                statusTV.setText("Login Failed, try again");
            }
        }


    }

我的界面改造

public interface geolocateApi {
@FormUrlEncoded
@POST("/login")
public boolean login(@Field("username") String username,@Field("password")  String password, Callback<UserModel> response);

}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您正在使用Retrofit进行回调,该回调基本上是异步发送请求。因此,当您的onPostExecute被执行时,改造请求可能仍在处理,将您的loginStatus保留为默认false值。您不需要AsyncTask,因为登录已经在后台运行。它应该是这样的

public class CheckLoginActivity extends Activity {

    static AlertDialog dialog;
    Button b;
    UserModel userModel;
    TextView statusTV;
    EditText userNameET, passWordET;
    String editTextUsername;
    boolean loginStatus;
    String editTextPassword;
    String API_URL = "http://192.168.42.60/task_manager/v1/index.php";
    SharedPreferences sharedpreferences;
    public static final String USERPREFERENCE = "userPreference";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_login);
        final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
        final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);
        usernameWrapper.setHint("Username");
        passwordWrapper.setHint("Password");
        dialog = new SpotsDialog(this, "Chargement");
        //NameText  control
        userNameET = (EditText) findViewById(R.id.editText1);
        passWordET = (EditText) findViewById(R.id.editText2);
        //Display Text control
        statusTV = (TextView) findViewById(R.id.tv_result);
        //Button to trigger web service invocation
        b = (Button) findViewById(R.id.button1);
        //Display progress bar until web service invocation completes
        //Button Click Listener
        sharedpreferences = getSharedPreferences(USERPREFERENCE, Context.MODE_PRIVATE);

        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //Check if text controls are not empty
                if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
                    if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") {
                        editTextUsername = userNameET.getText().toString();
                        editTextPassword = passWordET.getText().toString();
                        //        statusTV.setText("");
                        //Create instance for AsyncCallWS
                        RestAdapter restAdapter = new RestAdapter.Builder()
                                .setEndpoint(API_URL)
                                .build();
                        geolocateApi post = restAdapter.create(geolocateApi.class);

                        post.login(editTextUsername, editTextPassword, new Callback<UserModel>() {
                            @Override
                            public void success(UserModel userModelRecv, Response response) {
                                dialog.hide();
                                if (userModelRecv != null) {
                                    SharedPreferences.Editor editor = sharedpreferences.edit();
                                    editor.putString("username", userModelRecv.getUsername());
                                    editor.putString("id", userModelRecv.getUser_id());
                                    editor.putString("firstName", userModelRecv.getFirstName());
                                    editor.putString("lastName", userModelRecv.getLastName());
                                    editor.putString("Role", userModelRecv.getRole());
                                    userModel = userModelRecv;
                                    editor.commit();
                                    loginStatus = true;


                                    Intent intSucces = new Intent(CheckLoginActivity.this, HomeActivity.class);
                                    startActivity(intSucces);
                                } else {
                                    loginStatus = false;
                                    statusTV.setText("Login Failed, try again");
                                }
                            }

                            @Override
                            public void failure(RetrofitError error) {

                            }

                        });

                    }
                    //If Password text control is empty
                    else {
                        statusTV.setText("Please enter Password");
                    }
                    //If Username text control is empty
                } else {
                    statusTV.setText("Please enter Username");
                }
            }
        });
    }
}