我的 sharedPreference 总是 returns 默认值

My sharedPreference always returns default value

我知道这个问题被问过很多次了,很抱歉重复了一遍,但我只是不知道该怎么做。

我正在使用 Glide 从服务器加载图像到我的 RecycleView 并且它是监听器所以当我的图像被加载时,它应该保存 int 1 然后在我的片段中,我的 RecycleView 是,我得到那个 SharedPreferences int 并检查它是否不是 1 比我的 RecycleView xml 去 INVISIBLE/GONE 然后最后我检查我的一些 RecycleView 是 GONE/INVISIBLE 我的所有布局都应该消失,以便在加载所有图像后加载我的布局。

但是问题是我的SharedPreference里面的默认值总是触发,不知道为什么... 我也试过 PreferenceManager.getDefaultSharedPreferences() 但没什么不同。

我的适配器滑行:

Glide.with(context)
     .load(listaSvihMembersa.get(i).getImageUrl())
     .circleCrop()
     .placeholder(R.drawable.ic_joint)
     .listener(new RequestListener<Drawable>() {
         @Override
         public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
             return false;
         }

         @Override
         public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
             SharedPreferences sp = context.getSharedPreferences("mortgage", MODE_PRIVATE);
             sp.edit().putInt("motgageList", 1).apply();
             return true;
        }})
        .into(binding.detailedListIMG);
   }

和我获得 SharedPref 的片段

 private void setMortgageRecycleView(List<MortgageLiabilities> mortgageLiabilitiesList) {
    mortgageRecycleView = binding.rvMortgageList;
    mortgageRecycleView.animate().translationY(0);

    MortgageAdapter adapter = new MortgageAdapter(mortgageLiabilitiesList, context, this, listaSvihMembersa,mortgageRecycleView);
    mortgageRecycleView.setAdapter(adapter);
    SharedPreferences sp = context.getSharedPreferences("mortgage",MODE_PRIVATE);
    int idNmbr = sp.getInt("motgageList", 0);
    if (idNmbr != 1){
        mortgageRecycleView.setVisibility(View.INVISIBLE);
        Log.i(TAG, "visibility motgageListe: " + mortgageRecycleView.getVisibility());
    }
    else {
        mortgageRecycleView.setVisibility(View.VISIBLE);
        Log.i(TAG, "visibility motgageListe: " + mortgageRecycleView.getVisibility());
    }
    mortgageRecycleView.setLayoutManager(new LinearLayoutManager(context));
    mortgageRecycleView.setHasFixedSize(true);
}

在这里,我检查是否有任何 Recycleviews 是不可见的:

 if (mortgageRecycleView.getVisibility() == View.INVISIBLE || loansRecycleViews.getVisibility() == View.INVISIBLE
                    || otherRecycleView.getVisibility() == View.INVISIBLE || creditCardRecycleView.getVisibility() == View.INVISIBLE){
     binding.constraintLayout.setVisibility(View.GONE);
     Toast.makeText(context, "Ne moze da ucita,root view je GONE", Toast.LENGTH_SHORT).show();
 }

编辑:我的 shared_pref.xml 文件

<map>
    <int name="motgageList" value="1" />
</map>

Glide 正在执行异步任务,因此大多数情况下您的代码会在调用回调 onResourceReady 之前到达 int idNmbr = sp.getInt("motgageList", 0);

这里共享首选项不是一个好的选择,您可以使用自定义回调并将其传递给您的适配器。