Search code examples
javaandroidandroid-recyclerviewandroid-viewmodel

When and where is the right place to make a web request when using a ViewModel and RecyclerView inside a Fragment


In side of a Fragment I am loading data to a RecyclerView using ViewModel. My questing is where is the right place to make my web request. Right now I am doing it in the populateList in the ViewModel class, but it doesn't seem to load into the view right so I a wondering if maybe I should do that somewhere else?

ViewModel

public class twoViewModel  extends ViewModel {

    MutableLiveData<ArrayList<User>> userLiveData;
    ArrayList<User> userArrayList = new ArrayList<>();

    public twoViewModel() {

        userLiveData = new MutableLiveData<>();
        // call your Rest API in init method
        init();

    }

    public MutableLiveData<ArrayList<User>> getUserMutableLiveData() {
        if(userLiveData==null)
            userLiveData = new MutableLiveData<>();
        return userLiveData;
    }


    public void init(){
        populateList();
        getUserMutableLiveData().setValue(userArrayList);
    }

    public void populateList() {
              // Is this the right place?

        System.out.println("********* populateList *********");

   String url = "https://eliyah.com/wp-json/wp/v2/archive?page=1";

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
                (com.android.volley.Request.Method.GET, url, null, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {

                            JSONObject jObj = response.getJSONObject(0);
                            // Get title
                            String title = jObj.getJSONObject("title").getString("rendered");
                            String[] desc = {"06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)"};

                            User user = new User();
                            try {
                                user.setTitle(title);
                                user.setDescription(desc[0]);
                               

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            userArrayList.add(user);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                      // TODO figure out how to return userArrayList
                      
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error

                    }
                });
        MySingleton.getInstance(GlobleContextreRerence.instance.getApplicationContext()).addToRequestQueue(jsonArrayRequest);

Edit

In ViewModel:


 public void populateList() {
        System.out.println("********* populateList *********");


        WebRequest b = new WebRequest(userArrayList);
        userArrayList = b.getx();
}

Interface:


public interface VolleyCallBack {
    ArrayList<User> onSuccess(ArrayList<User> result);
}

Repository:

public class WebRequest implements VolleyCallBack {
    ArrayList<User> userArrayList;


    public WebRequest(ArrayList<User> userArrayList) {
        this.userArrayList = userArrayList;
    }


    @Override
    public ArrayList<User> onSuccess(ArrayList<User> userArrayList) {
        this.userArrayList = userArrayList;
        return userArrayList;
    }


    public ArrayList<User> fromAPI(final VolleyCallBack callBack) {

        String url = "https://eliyah.com/wp-json/wp/v2/archive?page=1";

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
                (com.android.volley.Request.Method.GET, url, null, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {

                            JSONObject jObj = response.getJSONObject(0);
                            // Get title
                            String title = jObj.getJSONObject("title").getString("rendered");
                          

                            String[] desc2 = {"06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)"};


                            User user = new User();
                            try {
                                user.setTitle(title);
                                user.setDescription(desc2[0]);
                           

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            userArrayList.add(user);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        callBack.onSuccess(userArrayList);
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error

                    }
                });


        MySingleton.getInstance(GlobleContextreRerence.instance.getApplicationContext()).addToRequestQueue(jsonArrayRequest);


        return userArrayList;

    }


    public ArrayList<User> getData() {
        ArrayList<User> arr;

        arr = fromAPI(new VolleyCallBack() {
            @Override
            public ArrayList<User> onSuccess(ArrayList<User> result) {

                return result;
            }
        });
        return arr;
    }

}

Solution

  • if you use android component(mvvm) is better make your request in datasource after that repository and viewmodel gets data from repository mvvm

    here is guide for mvvm