【问题标题】:Use shared Preference values in Repository or ViewModel of Android在 Android 的 Repository 或 ViewModel 中使用共享的 Preference 值
【发布时间】:2019-03-12 13:41:17
【问题描述】:

我在我的应用程序中使用ArchitectureComponents。我正在从ViewModel 发出API 请求,并在ActivityMain 中使用ViewModel 将数据设置为RecyclerView。为了进行Api 调用,我需要一个已保存的TokenSharedPreference。我需要在发出请求时获取该令牌并将其添加到标头中。在哪里以及如何获取 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);
    }  

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

【问题讨论】:

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


    【解决方案1】:
    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", "")
    
    }
    

    【讨论】:

    • 您可以为共享首选项创建单独的存储库。然后使用自定义工厂将其添加到您的视图模型中。检查这个arkapp.medium.com/…
    【解决方案2】:

    您可以将 Context 传递给 ViewModel,例如:

    ViewModel viewModel = new ViewModelProvider(this).get(UserViewModel.class);
       viewModel.setContext(new MutableLiveData<>(this));
    

    然后用它来获取任何活动资源。

    在 ViewModel 中:

    SharedPreferences sharedPref = context.getValue().getSharedPreferences("myPref",Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("token", token);
            editor.apply();
    

    【讨论】:

      【解决方案3】:

      您可以在存储库类的构造函数中创建一个 sharedPreference 对象。假设您已经制作了一个存储库类(Singleton)。

        //This class should be a singleton.
        public class YourRepositoryClass{
          //Initialize your token in your repository class's constructor
           String token=null;
          private YourRepositoryClass(Application application)
         {
           //your codes 
      
         //get your token in the repository and use whenever any viewmodel triggers repository to make a request
         // No need for getting token each time for different view models in case you are using multiple activities or fragments.
      
      
         SharedPreferences mPref=application.getSharedPreferences("preference_key",MODE_PRIVATE);
         token=mPref.getString("token",null);
      
      
              }
      
          // your other data request functions can be put here so that different view models can get data through this repository. Here use this token for making api requests.
      
        }
      

      您不必为每个视图模型一次又一次地调用 SharedPreferences,每个视图模型都可以使用存储库类轻松地请求特定数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 2022-11-10
        • 2023-03-17
        • 2022-12-03
        相关资源
        最近更新 更多