在 Android 的 Repository 或 ViewModel 中使用共享的 Preference 值
Use shared Preference values in Repository or ViewModel of Android
我在我的 application.I 中使用 ArchitectureComponents
从 ViewModel
发出 API
请求并在 ActivityMain.For 中使用 ViewModel 将数据设置为 RecyclerView
] 进行 Api 调用 我需要一个 Token
保存在 SharedPreference
中。我需要获取该令牌并将其添加到 Headers 中,同时进行 request.Where 和如何获取 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
中如何获取?
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", "")
}
您可以将 Context 传递给 ViewModel,例如:
ViewModel viewModel = new ViewModelProvider(this).get(UserViewModel.class);
viewModel.setContext(new MutableLiveData<>(this));
然后用它来获取activity的任何资源。
在视图模型中:
SharedPreferences sharedPref = context.getValue().getSharedPreferences("myPref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("token", token);
editor.apply();
您可以在存储库 class 中的构造函数中创建一个 sharedPreference 对象。假设您已经创建了一个存储库 class (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,并且每个视图模型都可以使用存储库轻松请求特定数据 class。
我在我的 application.I 中使用 ArchitectureComponents
从 ViewModel
发出 API
请求并在 ActivityMain.For 中使用 ViewModel 将数据设置为 RecyclerView
] 进行 Api 调用 我需要一个 Token
保存在 SharedPreference
中。我需要获取该令牌并将其添加到 Headers 中,同时进行 request.Where 和如何获取 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
中如何获取?
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", "")
}
您可以将 Context 传递给 ViewModel,例如:
ViewModel viewModel = new ViewModelProvider(this).get(UserViewModel.class);
viewModel.setContext(new MutableLiveData<>(this));
然后用它来获取activity的任何资源。
在视图模型中:
SharedPreferences sharedPref = context.getValue().getSharedPreferences("myPref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("token", token);
editor.apply();
您可以在存储库 class 中的构造函数中创建一个 sharedPreference 对象。假设您已经创建了一个存储库 class (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,并且每个视图模型都可以使用存储库轻松请求特定数据 class。