在 Android 的 Repository 或 ViewModel 中使用共享的 Preference 值

Sat*_*ale 4 android sharedpreferences android-recyclerview android-architecture-components

ArchitectureComponents在我的应用程序中使用。我正在使用 ActivityMain 中的 ViewModel发出API请求ViewModel并将数据设置为RecyclerView使用 ViewModel。为了进行 Api 调用,我需要一个Token保存在SharedPreference.I 中的令牌。我需要获取该令牌并将其添加到标题中,同时发出请求。哪里以及如何获取 SharedPreference 值。它应该在 ViewModel 或 Repository 中。
这是我的代码ViewModel

public class FoodieViewModel extends AndroidViewModel {
   FoodieRepository repository;
   MutableLiveData<ArrayList<Foodie>> foodieList;
    public FoodieViewModel(@NonNull Application application) {
        super(application);
        repository=new FoodieRepository(application);
    }

     LiveData<ArrayList<Foodie>> getAllFoodie(){
        if(foodieList==null){
            foodieList=new MutableLiveData<ArrayList<Foodie>>();
            loadFoodies();
        }
        return foodieList;
    }
    public void loadFoodies(){
        String url="somethimg.com";
        JsonArrayRequest request =new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                ArrayList<Foodie> list=new ArrayList<>();
                try {
                    for(int i=0;i<response.length();i++){
                        JSONObject obj=response.getJSONObject(i);
                        Foodie foodie=new Foodie();
                        String name=obj.getString("firstname");
                        foodie.setName(name);
                        list.add(foodie);
                    }

                }catch (JSONException e){
                    e.printStackTrace();
                }
                foodieList.setValue(list);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                String auth = "JWT " + "sometoken";
                headers.put("Authorization", auth);
                headers.put("Content-Type", "application/json");
                return headers;
            }

        };
        AppController.getInstance().addToRequestQueue(request);
    }  
Run Code Online (Sandbox Code Playgroud)

如果存储在 Token 中,如何获取 Token SharedPreference

Sur*_*wal 6

public class FoodieViewModel extends AndroidViewModel {
........
SharedPreferences sharedpreferences =getApplication().getSharedPreferences("preference_key", Context.MODE_PRIVATE);
...........

//wherever u want to get token
String token = sharedpreferences.getString("token", "")

}
Run Code Online (Sandbox Code Playgroud)

  • 该文章使用 Activity/Fragment 中的存储库。根据我的理解,所有业务逻辑,包括依赖于 SharedPreferences 变量值的“值 x 或 y”问题,都是在 ViewModel 中完成的,而不是在 Activity/Fragments 中完成的。浏览大量帖子,似乎使用存储库中的共享首选项的唯一正确方法是从 AndroidViewModel 获取应用程序上下文(如上所述),然后在视图模型中使用该应用程序上下文手动实例化“MyAppDataRepository”。 (2认同)