在Android的存储库或ViewModel中使用共享的首选项值

时间:2019-03-12 13:41:18

标签: android android-recyclerview sharedpreferences android-architecture-components

我在应用程序中使用ArchitectureComponents。我正在API发出ViewModel请求,并使用ActivityMain中的ViewModel将数据设置为RecyclerView。需要保存在Token中的SharedPreference。我需要获取该令牌并将其添加到标头中,同时发出请求。在何处以及如何获取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);
    }  

如果令牌存储在SharedPreference中,如何获取令牌?

1 个答案:

答案 0 :(得分:2)

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", "")

}