java共享的首选项值没有立即更新

g6ll5ycj  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(419)

当用户登录时,我从api获取了一些数据,我想立即更新一些视图值。但是使用共享首选项并不是第一次工作,用户应该关闭应用程序,并且在这种情况下更新了共享首选项值。如何在不关闭应用程序的情况下更新从其他活动中的api检索到的值?这是我的密码

public class AppController extends Application {
  public static SharedPreferences userSharedPreferences;
  public static SharedPreferences.Editor userEditor;

  public void onCreate() {
        super.onCreate();
        userSharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
        //userSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        userEditor = userSharedPreferences.edit();
  }
}

public class ParseLogin {
        JSONObject json = new JSONObject(jsonObject.toString());
        JSONObject resultObject = json.getJSONObject("Result");
        JSONObject baseObject = resultObject.getJSONObject("Base");
        //SharedPreferences.Editor userEditor = context.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
        SharedPreferences.Editor userEditor = AppController.userEditor;

        userEditor.putString("UserName", baseObject.getString("UserName"));
        userEditor.putString("MobileNumber", baseObject.getString("Mobile"));
        userEditor.putString("FirstName", baseObject.getString("FirstName"));
        userEditor.putString("LastName", baseObject.getString("LastName"));
        userEditor.putString("Avatar", baseObject.getString("Avatar"));
        userEditor.putString("Email", baseObject.getString("Email"));
        userEditor.putString("Gender", baseObject.getString("Gender"));
        userEditor.putString("Datebirth", baseObject.getString("Datebirth"));
        userEditor.apply();
        SharedPreferences.Editor editor = context.getSharedPreferences("const", Context.MODE_PRIVATE).edit();
        editor.putString("PaymentUrl", resultObject.getString("PaymentUrl"));
        editor.putString("FararuUrl", resultObject.getString("FararuUrl"));
        editor.putString("ForgetPasswordUrl", resultObject.getString("ForgetPasswordUrl"));
        editor.apply();
        Log.i("test_sp", AppController.userSharedPreferences.getString("FirstName", ""));
}

public class LoginFragment extends Fragment implements View.OnClickListener {
   @Override
    public void onClick(View v) {
       mLoginViewModel.login(v, et_username.getText().toString(),
                            et_pass.getText().toString(), getContext()).observe(this,
                            new Observer<Boolean>() {
                        @Override
                        public void onChanged(@Nullable Boolean isLogin) {
                            if (isLogin) {
                                mLoginViewModel.getBaseData().observe(LoginFragment.this,
                                        new Observer<Boolean>() {
                                    @Override
                                    public void onChanged(@Nullable Boolean aBoolean) {
                                        dialog.dismiss();
                                        Intent intent = new Intent(mContext, MainActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                                        getActivity().finish();
                                        startActivity(intent);
                                        Toast.makeText(mContext, R.string.logsuccess, Toast.LENGTH_SHORT).show();
                      }
                    });
                 } else {
                   dialog.dismiss();
                 }
           }
        });
    }
}

public class LoginViewModel extends AndroidViewModel {
  public LiveData<Boolean> getBaseData() {
        LoginRepository loginRepository = new LoginRepository();
        return loginRepository.getBaseData(getApplication());
  }
}

public class LoginRepository {
   public LiveData<Boolean> getBaseData(final Context context) {
        BaseService loginService = new BaseService();
        final MutableLiveData<Boolean> loginStatusLiveData = new MutableLiveData<>();
        String token = context.getSharedPreferences("user", Context.MODE_PRIVATE).getString("Api-Token", "");
        Log.i("token_val", token);
        Call<JsonObject> call = loginService.getRetrofit().create(UserLoginApi.class).getBaseData(token);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

                try {
                    assert response.body() != null;
                    ParseLogin parseLogin = new ParseLogin();
                    int code = parseLogin.getCode(response.body());
                    if (code == 200) {
                        parseLogin.getBaseData(context, new JSONObject(response.body().toString()));
                        logUser(context);
                        loginStatusLiveData.postValue(true);
                        FireBaseRepository fireBaseRepository = new FireBaseRepository();
                        fireBaseRepository.sendFireBaseToken(context);
                        Log.e(this.getClass().getName(), "user is login");
                    } else if (code == 401 || code == 403) {
                        loginStatusLiveData.postValue(false);
                        Log.e(this.getClass().getName(), "401,403");
                    } else {
                        loginStatusLiveData.postValue(true);
                        Log.e(this.getClass().getName(), "other");
                    }

                } catch (JSONException | NullPointerException e) {
                    e.printStackTrace();
                    Log.e(this.getClass().getName(), "json error");
                    Log.e(this.getClass().getName(), e.getMessage() + "");
                    loginStatusLiveData.postValue(true);
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.e(this.getClass().getName(), t.getMessage() + "");
                Log.e(this.getClass().getName(), "failure error");
                loginStatusLiveData.postValue(true);
            }
        });
        return loginStatusLiveData;
    }
}

public class MainActivity extends AppCompatActivity {
   @Override
    protected void onResume() {
        super.onResume();

        //SharedPreferences pref = getSharedPreferences("user", MODE_PRIVATE);
        SharedPreferences pref = AppController.userSharedPreferences;
        String fname = pref.getString("FirstName", "");
        String lname = pref.getString("LastName", "");
        tv_username.setText(fname + " " + lname);
    }
}
nxowjjhe

nxowjjhe1#

您正在使用apply()方法更新SharedReference,它是异步方法。
如果要立即更新数据,请使用commit()

相关问题