如何在Retrofit2 onResponse方法中使用SharedPreferences?

时间:2018-01-19 09:41:01

标签: android json sharedpreferences retrofit2 android-sharedpreferences

我正在尝试在登录时获取用户的登录凭据。我发送到我的数据库User_Email和User_Password,然后返回如下所示的Json。实际上问题很简单,但我不知道解决方案,我有点新。 我%100肯定我的onResponse方法中的错误。因为我看到这个成功的响应Toast,所以我成功回复但问题在这里我不知道如何将这个Json响应变成共享偏好。感谢

{
    "User": [
        {
            "SSN": "123456789",
            "FirstName": "Furkan",
            "User_Role": "1"
        }
    ]
}

这个回复的模型类是:

public class UserList {

    @SerializedName("User")
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

public class User {
    @SerializedName("SSN")
    public String sSN;
    @SerializedName("FirstName")
    public String firstName;
    @SerializedName("User_Role")
    public intuserRole;

    public String getsSN() {
        return sSN;
    }

    public void setsSN(String sSN) {
        this.sSN = sSN;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public int getUserRoleTypeId() {
        return userRoleTypeId;
    }

    public void setUserRoleTypeId(int userRoleTypeId) {
        this.userRoleTypeId = userRoleTypeId;
    }
}

我正在尝试将这些userRoleTypeId,firstName和sSN添加到我的call.enqueue onResponse中的SharedPreferences。但我无法理解。

这是我登录的LoginActivity.class:

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

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 ....");

        sharedPreferences = getApplicationContext().getSharedPreferences("LoginActivity",MODE_PRIVATE);

 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);
                    this.userRoleTypeId = sharedPreferences.getInt(Constants.USERROLE, 0);
                    if (userRoleTypeId == 1) {
                        intent = new Intent(this, OrganizerHomeActivity.class);
                        startActivity(intent);
                    } else if(userRoleTypeId == 2 || userRoleTypeId == 3) {
                        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) {
                //I am sure the fault in here. In below i tried to take Json response and fetch it into the Shared Preferences.
                UserList userLists = response.body().getUser();
                if(response.isSuccessful()){
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean(Constants.IS_LOGGED_IN, true);
                   // editor.putString(Constants.NAME, userLists.getFirstName);
                    //editor.putString(Constants.SSN, userLists.getsSN);
                   // editor.putInt(Constants.USERROLE, userLists.getuserRoleTypeId);
                    editor.apply();


    // I am seeing this successfull response toast, so i am getting successfull response but the problem here i dont know how to get this Json response into sharedpref.
Toast.makeText(LoginActivity.this, "successfull response", 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();
            }
        });

    }
}

1 个答案:

答案 0 :(得分:1)

试试这个

    if(response.isSuccessful()){
                List<User> userLists = response.body().getUser();
    SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = settings.edit();
    editor.putBoolean(Constants.IS_LOGGED_IN, true);
    prefeditor.putString("UserName", userLists.getUser().getFirstName());
    prefEditor.putString(Constants.SSN, userLists.getUser().getsSN());
    prefEditor.putInt(Constants.USERROLE, userLists.getUser().getUserRoleTypeId());
    prefEditor.commit();
            }