简体   繁体   English

共享首选项值未立即更新

[英]Shared Preferences values was not updated immediately

I get some data from api when user logs in and I want to update some views values immediately.but using shared preferences does not work for first time and user should close the app and shared preferences values was updated in that case.How can I update retrieved values from api in another activities without closing apps?我在用户登录时从 api 获取了一些数据,我想立即更新一些视图值。但是第一次使用共享首选项不起作用,用户应该关闭应用程序并且在这种情况下更新了共享首选项值。我该如何更新在不关闭应用程序的情况下从另一个活动中的 api 检索值? Here is my code这是我的代码

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);
    }
}

You are using apply() method to update the sharedpreference, it is async method.您正在使用apply()方法来更新共享首选项,它是异步方法。

If you want an immediate update of the data, use commit()如果您想立即更新数据,请使用commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM