如何在同一活动中检索共享首选项,它是空的?

时间:2018-01-20 14:31:05

标签: android sharedpreferences retrofit2

在我的应用程序的登录屏幕中,我在我的retrofit2 onResponse 方法的共享首选项中提取 JSON 响应。我从数据库获取正确的所有内容,并将其正确放入共享 偏好设置。我从db获取 User_Role 作为字符串,然后基于User_Role,我将用户指向相应的活动。 我需要在R.id.Login:步骤中达到User_Role。在我的Logcat中,我看到我的回答是我想要的。如果我能设法正确放置首选项,我会在提交首选项后检查Toast。是的,这是写入屏幕response.success组织者。所以唯一的问题是我无法检索它。请帮忙。

因为我的apicall中的所有内容都正常工作(因为我在屏幕上用 Toast.makeText.show(); 检查了每一步)我只是将我的LoginActivity.class代码放在下面,

LoginActivity.class:

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    Button bSignUp, bLogin;
    EditText etPassword, etEmail;
    private ProgressDialog progressDialog;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        bSignUp = (Button) findViewById(R.id.bSignUp);
        bLogin = (Button) findViewById(R.id.bLogin);
        bSignUp.setOnClickListener((View.OnClickListener) this);
        bLogin.setOnClickListener((View.OnClickListener) this);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etEmail = (EditText) findViewById(R.id.etEmail);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Logging in");
        progressDialog.setMessage("Please wait ....");

        bLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.bSignUp:
                Intent SignUpIntent = new Intent(this, SignUpActivity.class);
                startActivity(SignUpIntent);
                break;

            case R.id.bLogin:

                String email = etEmail.getText().toString();
                String password = etPassword.getText().toString();
                if (!email.isEmpty() && !password.isEmpty()) {
                    progressDialog.show();
                    loginProcess(email, password);

    //Here i need to obtain SharedPreferences that i filled in onResponse Method. It goes directly wrong email or password statement. Because of can't retrieve settings.getString("User_Role","")

                        SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
                        String userRole = settings.getString("User_Role","");
                        Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();

                        if (userRole.equals("Organizator")) {
                            intent = new Intent(this, OrganizerHomeActivity.class);
                            startActivity(intent);

                        } else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
                            intent = new Intent(this, UserHomeActivity.class);
                            startActivity(intent);
                        }
                        else{
                            Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
        }
    }

    private void loginProcess(String email, String password) {
        LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
        retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
        call.enqueue(new Callback<UserList>(){
            @Override
            public void onResponse(Call<UserList> call, Response<UserList> response) {
                if(response.isSuccessful()){
                    List<User> userLists = response.body().getUser();
                    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    //SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
                    SharedPreferences.Editor prefEditor = settings.edit();
                    prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
                    prefEditor.putString("UserName", userLists.get(0).getFirstName());
                    prefEditor.putString("SSN", userLists.get(0).getsSN());
                    prefEditor.putString("User_Role", userLists.get(0).getUserRole());
                    prefEditor.commit();
                    // In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
                    Toast.makeText(LoginActivity.this, "response.success  "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<UserList> call, Throwable t) {
                Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        });
    }
}

2 个答案:

答案 0 :(得分:1)

在onResponse成功之后放置您的SharedPreference逻辑。它是因为它在您的回复得到之前执行。这就是为什么它是空的。所以改变这样的代码

private void checkMethod(){

                    SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
                    String userRole = settings.getString("User_Role","");
                    Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();

                    if (userRole.equals("Organizator")) {
                        intent = new Intent(this, OrganizerHomeActivity.class);
                        startActivity(intent);

                    } else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
                        intent = new Intent(this, UserHomeActivity.class);
                        startActivity(intent);
                    }
                    else{
                        Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
                }
}

并从onResponse调用此方法,如下所示

public void onResponse(Call<UserList> call, Response<UserList> response) {
            if(response.isSuccessful()){
                List<User> userLists = response.body().getUser();
                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                //SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
                SharedPreferences.Editor prefEditor = settings.edit();
                prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
                prefEditor.putString("UserName", userLists.get(0).getFirstName());
                prefEditor.putString("SSN", userLists.get(0).getsSN());
                prefEditor.putString("User_Role", userLists.get(0).getUserRole());
                prefEditor.commit();
                // In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
                Toast.makeText(LoginActivity.this, "response.success  "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();

                checkMethod();

}

答案 1 :(得分:1)

尝试在响应方法中启动intent条件。无需在共享首选项中存储值。