【问题标题】:Method called before the initialization of an Adapter , executing after the adapter initialization in Android在适配器初始化之前调用的方法,在Android中适配器初始化之后执行
【发布时间】:2016-03-10 07:28:43
【问题描述】:

在我的 Fragment onCreateView 方法中,我调用了一个名为 getData() 的方法,该方法已实现使用 android volley 库从服务器获取一些数据作为 json 响应。

getData()方法:

public void getData(MyCustomListener<CompleteCartProItem> customListener) {
    if (MyApplication.getAndroidSession().getAttribute("cart") != null) {
        Log.i("cart_null", "NOT null");
        RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
        CartDetails cartDetails = (CartDetails) MyApplication.getAndroidSession().getAttribute("cart");
        ArrayList<CartItem> jsonSendArray = cartDetails.getShoppingList();
        final String jsonString = new Gson().toJson(jsonSendArray,
                new TypeToken<ArrayList<CartItem>>() {
                }.getType());

        Log.i("json_object", jsonString); 

        String url = "http://10.0.2.2:8080/ECommerceApp/getAllProductsAction";
        JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, url,
                response -> {
                    List<CompleteCartProItem> completeCart = new Gson().fromJson(response.toString(),
                            new TypeToken<List<CompleteCartProItem>>() {
                            }.getType());
                    Log.i("response", completeCart.get(0).getP_name());// successfully prints out the 0th product name.
                    customListener.onResponse(completeCart);

                }, error -> Log.i("Volley_error", error.getMessage())) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type", "application/json");
                params.put("cartList", jsonString);
                return params;
            }

        };
        arrayRequest.setRetryPolicy(new RetryPolicy() {
            @Override
            public int getCurrentTimeout() {
                return 5000;
            }

            @Override
            public int getCurrentRetryCount() {
                return 5000;
            }

            @Override
            public void retry(VolleyError error) throws VolleyError {

            }
        });
        requestQueue.add(arrayRequest);
    } else {
        Log.i("cart_null", "null");
    }


}

内部onCreateView

    ...

    getData(new MyCustomListener<CompleteCartProItem>() {
        @Override
        public void onResponse(List<CompleteCartProItem> response) {
            completeCartProItems.addAll(response);
            Log.i("executed", "Inside_onResponse");
            Log.i("check", completeCartProItems.get(0).getP_name());

        }

        @Override
        public void onError(String error_response) {

        }
    });

    cart_item_scrollerAdapter = new CartItem_ScrollerAdapter(getActivity(), completeCartProItems);//completeCartProItems is an ArrayList of CompleteCartProItem (private List<CompleteCartProItem> completeCartProItems = new ArrayList<>();)

    ...

如您所见,我在初始化适配器之前调用了getData()。但是CartItem_ScrollerAdapter(...) 构造函数在getData() 方法之前调用。

CartItem_ScrollerAdapter(...) 的构造函数:

public CartItem_ScrollerAdapter(Context context, List<CompleteCartProItem> completeCartProItems) {
    this.inflater = LayoutInflater.from(context);
    this.context = context;
    this.completeCartProItems = completeCartProItems;
    Log.i("executed","Adapter");
}

如您所见,getData() 方法内部的Log.i("executed", "Inside_onResponse"); 在显示CartItem_ScrollerAdapter(...) 内部的Log.i("executed","Adapter"); 之后显示在日志猫中。在此之前我还没有在任何地方初始化它。所以这导致我的completeCartProItems ArrayList 传递给CartItem_ScrollerAdapter(...) 的构造函数总是空的。任何摆脱这个问题的建议都会很明显。谢谢你。

【问题讨论】:

    标签: android android-asynctask android-volley


    【解决方案1】:

    在调用getData() 之前初始化适配器。并且当接收到数据时,将其添加到ArrayList并调用适配器的notifyDataSetChanged();

    // completeCartProItems should be initialized before passing it into adapter.
    cart_item_scrollerAdapter = new CartItem_ScrollerAdapter(getActivity(), completeCartProItems);
    // Set your adatper here...
    cart_horizontal_scroller.setAdapter(cart_item_scrollerAdapter); 
    
    getData(new MyCustomListener<CompleteCartProItem>() {
            @Override
            public void onResponse(List<CompleteCartProItem> response) {
                completeCartProItems.addAll(response);
                cart_item_scrollerAdapter.notifyDataSetChanged();
                Log.i("executed", "Inside_onResponse");
                Log.i("check", completeCartProItems.get(0).getP_name());
    
            }
    
            @Override
            public void onError(String error_response) {
    
            }
        });
    

    【讨论】:

    • 这就像一个魅力。你拯救了我的一天.. 非常感谢.. :) 我在这里stackoverflow.com/q/35835338/5454585 以不同的方式提出了这个问题。但无法得到正确的解决方案。无论如何,再次感谢你..
    猜你喜欢
    • 2012-11-25
    • 2013-09-09
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2017-08-28
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多