Я использую ArchitectureComponents в своем приложении. Я делаю запрос API из ViewModel и устанавливаю данные в RecyclerView, используя ViewModel в ActivityMain. Для вызова API мне нужен 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?
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", "")
}
Вы можете передать контекст в 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();
Вы можете создать объект 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 для каждой модели представления, и каждая модель представления может легко запрашивать определенные данные с помощью класса репозитория.
Вы можете создать отдельный репозиторий для общих настроек. Затем добавьте это в свою модель представления, используя пользовательскую фабрику. Проверьте этот arkapp.medium.com/…