【问题标题】:When and where is the right place to make a web request when using a ViewModel and RecyclerView inside a Fragment在 Fragment 中使用 ViewModel 和 RecyclerView 时,何时何地是发出 Web 请求的正确位置
【发布时间】:2021-06-27 05:21:30
【问题描述】:

在片段的一侧,我正在使用ViewModel 将数据加载到RecyclerView。我的任务是提出我的网络请求的正确位置。现在我正在 ViewModel 类的 populateList 中执行此操作,但它似乎没有正确加载到视图中,所以我想知道是否应该在其他地方执行此操作?

视图模型

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);

编辑

在 ViewModel 中:


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


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

界面:


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

存储库:

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;
    }

}

【问题讨论】:

    标签: java android android-recyclerview android-viewmodel


    【解决方案1】:

    如果您使用 android 组件(mvvm),最好在该存储库和 viewmodel 从存储库 mvvm 获取数据之后在数据源中提出您的请求

    here is guide for mvvm

    【讨论】:

    • 谢谢,但是除了这里 developer.android.com/guide/background/threading> 之外,该链接没有显示如何在 java 中执行此操作,这与我正在做的事情相去甚远。我尝试使用存储库,但它没有给我足够的信息。查看我的编辑。
    • 你可以搜索关于android mvvm java
    • 谢谢,我想你必须知道要找什么才能找到它。该视频对解释我不理解的内容非常有帮助。视频:youtube.com/watch?v=xPi-z3nOcn8>.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 2021-02-24
    • 2017-05-15
    • 2022-01-04
    相关资源
    最近更新 更多