从SharedPreferences迁移到Jetpack数据存储“Java”

根据这个问题,我试图将当前项目从SharedPreferences到dataStore存储用户选择的布局的值,问题是读取值,我得到NPE首先这是我的代码

内部DataStoreRepository类

public class Utils {
/*
* Some unrelated codes
*/
public static class DataStoreRepository {
        RxDataStore<Preferences> dataStore;
        public DataStoreRepository(Context context) {
            dataStore =
                    new RxPreferenceDataStoreBuilder(Objects.requireNonNull(context), /*name=*/ "settings").build();
        }
        public Preferences.Key<String> RECYCLER_VIEW_LAYOUT_KEY;
        public void saveValue(String keyName, String value) {
            RECYCLER_VIEW_LAYOUT_KEY = PreferencesKeys.stringKey(keyName);
            dataStore.updateDataAsync(prefsIn -> {
                MutablePreferences mutablePreferences = prefsIn.toMutablePreferences();
                String currentKey = prefsIn.get(RECYCLER_VIEW_LAYOUT_KEY);
                if (currentKey == null) {
                    saveValue(keyName, value);
                }
                mutablePreferences.set(RECYCLER_VIEW_LAYOUT_KEY,
                        currentKey != null ? value : "cardLayout");
                return Single.just(mutablePreferences);
            }).subscribe();
           // The update is completed once updateResult is completed.
        }
        public Flowable<String> readLayoutFlow =
                dataStore.data().map(prefs -> prefs.get(RECYCLER_VIEW_LAYOUT_KEY));
    }
}

我把它用在这样的片段里

首先我读了流动

private Utils.DataStoreRepository dataStoreRepository;
private String layout2;
public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        dataStoreRepository = new Utils.DataStoreRepository(requireContext());
            dataStoreRepository.readLayoutFlow.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new FlowableSubscriber<String>() {
                        @Override
                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Subscription s) {
                        }
                        @Override
                        public void onNext(String layout) {
                            layout2 = layout;
                        }
                        @Override
                        public void onError(Throwable t) {
                            Log.e(TAG, "onError: " + t.getMessage());
                        }
                        @Override
                        public void onComplete() {
                        }
                    });

然后在同一个类中,我将值存储在方法changeAndSaveLayout()上

private void changeAndSaveLayout() {
        android.app.AlertDialog.Builder builder
                = new android.app.AlertDialog.Builder(getContext());
        builder.setTitle(getString(R.string.choose_layout));
        String[] recyclerViewLayouts = getResources().getStringArray(R.array.RecyclerViewLayouts);
//        SharedPreferences.Editor editor = sharedPreferences.edit();
        builder.setItems(recyclerViewLayouts, (dialog, index) -> {
            switch (index) {
                case 0: // Card List Layout
                    adapter.setViewType(0);
                    binding.homeRecyclerView.setLayoutManager(layoutManager);
                    binding.homeRecyclerView.setAdapter(adapter);
//                    editor.putString("recyclerViewLayout", "cardLayout");
//                    editor.apply();
                    dataStoreRepository.saveValue("recyclerViewLayout","cardLayout");
                    break;
                case 1: // Cards Magazine Layout
                    adapter.setViewType(1);
                    binding.homeRecyclerView.setLayoutManager(layoutManager);
                    binding.homeRecyclerView.setAdapter(adapter);
//                    editor.putString("recyclerViewLayout", "cardMagazineLayout");
//                    editor.apply();
                    dataStoreRepository.saveValue("recyclerViewLayout","cardMagazineLayout");
                    break;
                case 2: // PostTitle Layout
                    adapter.setViewType(2);
                    binding.homeRecyclerView.setLayoutManager(titleLayoutManager);
                    binding.homeRecyclerView.setAdapter(adapter);
//                    editor.putString("recyclerViewLayout", "titleLayout");
//                    editor.apply();
                    dataStoreRepository.saveValue("recyclerViewLayout","titleLayout");
                    break;
                case 3: //Grid Layout
                    adapter.setViewType(3);
                    binding.homeRecyclerView.setLayoutManager(gridLayoutManager);
                    binding.homeRecyclerView.setAdapter(adapter);
//                    editor.putString("recyclerViewLayout", "gridLayout");
//                    editor.apply();
                    dataStoreRepository.saveValue("recyclerViewLayout","gridLayout");
            }
        });
        android.app.AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

当我运行时,我得到了这个NPE,它关于读取值readLayoutFlow,我尝试在方法之外创建键,像这样

public Preferences.Key<String> RECYCLER_VIEW_LAYOUT_KEY = PreferencesKeys.stringKey("recyclerViewLayout");

在saveValue()中像这样改变它的值但它也不起作用

RECYCLER_VIEW_LAYOUT_KEY.to(keyName);

NPE的输出

 Process: com.blogspot.abtallaldigital, PID: 9184
    java.lang.NullPointerException: Attempt to invoke virtual method 'io.reactivex.rxjava3.core.Flowable androidx.datastore.rxjava3.RxDataStore.data()' on a null object reference
        at com.blogspot.abtallaldigital.utils.Utils$DataStoreRepository.<init>(Utils.java:4)
        at com.blogspot.abtallaldigital.ui.home.HomeFragment.onCreateView(HomeFragment.java:10)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:4)
        at androidx.fragment.app.FragmentStateManager.f(FragmentStateManager.java:15)
        at androidx.fragment.app.FragmentStateManager.l(FragmentStateManager.java:20)
        at androidx.fragment.app.FragmentStore.s(FragmentStore.java:3)
        at androidx.fragment.app.FragmentManager.h0(FragmentManager.java:6)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3)
        at androidx.fragment.app.FragmentManager.G(FragmentManager.java:1)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2)
        at androidx.fragment.app.FragmentStateManager.f(FragmentStateManager.java:26)
        at androidx.fragment.app.FragmentStateManager.l(FragmentStateManager.java:20)
        at androidx.fragment.app.FragmentStore.s(FragmentStore.java:3)
        at androidx.fragment.app.FragmentManager.h0(FragmentManager.java:6)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3)
        at androidx.fragment.app.FragmentManager.m(FragmentManager.java:4)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:1)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:6)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:1)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
        at android.app.Activity.performStart(Activity.java:8018)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

### NullPointerException的原因是初始化readLayoutFlow before dataStore.
之前dataStore.
。< br / >

的代码

public Flowable<String> readLayoutFlow =
                dataStore.data().map(prefs -> prefs.get(RECYCLER_VIEW_LAYOUT_KEY));

在执行构造函数代码之前求值。因此dataStore为空,并抛出NullPointerException。

一个简单的解决方案是像这样将readLayoutFlow的初始化移到构造函数中:

public static class DataStoreRepository {
    RxDataStore<Preferences> dataStore;
    
    public final Flowable<String> readLayoutFlow;
    public DataStoreRepository(Context context) {
        dataStore = new RxPreferenceDataStoreBuilder(
                            Objects.requireNonNull(context),
                            /*name=*/ "settings")
                        .build();
        readLayoutFlow = dataStore.data()
            .map(prefs -> prefs.get(RECYCLER_VIEW_LAYOUT_KEY));
    }
    \\ other code
}

编辑:第一次启动时的空白屏幕

有两种不同的情况。这两个问题我都要回答:

安装应用程序后首先启动

为了在第一次启动时设置布局,我建议为首选项设置一个默认值,在第一次启动时保存(设置一个booleanPreferencesKey来检查它是否是第一次启动)。

重新启动应用程序

如果每次新启动应用程序时都出现黑屏,你可能没有检查片段onViewCreated中当前设置的首选项。就我个人而言,我会使用MutableLiveData<在Fragment中的recyclerViewLayoutPreference观察preference像这样:

private MutableLiveData<String> recyclerViewLayoutPreference;
@Override
public void onCreate(/*params*/) {
    super.onCreate(/*params*/);
    recyclerViewLayoutPreferences = new MutableLiveData<>();
}
@Override
public void onViewCreated(/*params*/) {
    super.onViewCreated(/*params*/),
    dataStoreRepository.readLayoutFlow()
        .subscribeOn(Schedulers.io())
        .doOnNext(recyclerViewLayoutPreference::postValue)
        .subscribe();
    recyclerViewLayoutPreference.observe(getViewLifecycleOwner(), layoutString -> {
        if (layoutString == null) return;
        switch (layoutString) {
            case "cardLayout":
                adapter.setViewType(0);
                binding.homeRecyclerView.setLayoutManager(layoutManager);
                    binding.homeRecyclerView.setAdapter(adapter);
            /* other cases */
        }
    });
}

这样,在changeAndSaveLayout的情况下,你只需要调用dataStoreRepository。saveValue(…),并且使用LiveData将必要的生命周期事件管理保持在最低限度。

阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码