I am using ArchitectureComponents
in my application.I am making API
request from ViewModel
and setting data to RecyclerView
using ViewModel in ActivityMain.For making a Api call I need a Token
which is saved in SharedPreference
.I need to get that token and add it in Headers while making request.Where and how to get the SharedPreference value. It should be get in ViewModel or Repository.
This is code for my 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);
}
How to get the Token if it is stored in 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", "")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With