如何检查 Recyclerview 是不是为空

Posted

技术标签:

【中文标题】如何检查 Recyclerview 是不是为空【英文标题】:How to check is Recyclerviews is empty如何检查 Recyclerview 是否为空 【发布时间】:2017-11-15 19:34:31 【问题描述】:

您好,我在 cardviews 中有一个 recyclerview,我通过 volley 请求从服务器(JSONobjects)获取数据。如何检测我的回收站视图是否为空?我试图检查 ArrayList 是否为空,但似乎不起作用,我该如何解决?谢谢

这是我的片段:

public class Tab1History extends Fragment implements SwipeRefreshLayout.OnRefreshListener


SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView recyclerView;
private CespiteAdapter adapter;
UserSessionManager session;
ConnectionDetector cd;

private static final String URL_DATA = "http://myfile.php";

private List<CespiteOgg> cespiteOggList;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)

    cd = new ConnectionDetector(getActivity());
    View rootView = inflater.inflate(R.layout.tab1history, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
    recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    cespiteOggList = new ArrayList<>();

    // SwipeRefreshLayout
    mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorSchemeResources(
            R.color.colorAccent
            );

    /**
     * Showing Swipe Refresh animation on activity create
     * As animation won't start on onCreate, post runnable is used
     */
    mSwipeRefreshLayout.post(new Runnable() 

        @Override
        public void run() 

            mSwipeRefreshLayout.setRefreshing(true);

            // Fetching data from server
            loadRecyclerViewData();
        
    );

    return rootView;

/**
 * This method is called when swipe refresh is pulled down
 */
@Override
public void onRefresh()

    if(cd.isNetworkAvailable())
    
        // Fetching data from server
        loadRecyclerViewData();
    
    else
    
        Toast.makeText(getActivity(), "Nessuna connessione ad internet!", Toast.LENGTH_SHORT).show();
        mSwipeRefreshLayout.setRefreshing(false);
    



private void loadRecyclerViewData()


    cespiteOggList.clear();
    //cespiteOggList = new ArrayList<>();
    // Showing refresh animation before making http call
    mSwipeRefreshLayout.setRefreshing(true);

    // Session class instance
    session = new UserSessionManager(getActivity());
    //get user data from session
    HashMap<String, String> user = session.getUserDetails();
    //get name
    String name = user.get(UserSessionManager.KEY_NAME);
    // get username
    final String usernameUtente = user.get(UserSessionManager.KEY_USERNAME);


    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            URL_DATA,
            new Response.Listener<String>() 
                @Override
                public void onResponse(String s) 

                    try 
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray array = jsonObject.getJSONArray("dates");

                        for(int i=0; i<array.length(); i++)
                        
                            JSONObject o = array.getJSONObject(i);
                            CespiteOgg item = new CespiteOgg(
                                    o.getString("CodNumInventario"),
                                    o.getString("Nome"),
                                    o.getString("DtCatalogazione"),
                                    o.getString("CodIdA"),
                                    o.getString("username")
                            );
                            cespiteOggList.add(item);
                        

                        adapter = new CespiteAdapter(cespiteOggList, getActivity());
                        recyclerView.setAdapter(adapter);

                     catch (JSONException e) 
                        e.printStackTrace();
                    

                    // Stopping swipe refresh
                    mSwipeRefreshLayout.setRefreshing(false);

                
            ,
            new Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 

                    // Stopping swipe refresh
                    mSwipeRefreshLayout.setRefreshing(false);

                
            )
    
        @Override
        protected Map<String, String> getParams() throws AuthFailureError 
            Map<String, String> params = new HashMap<String, String>();
            params.put("Username", usernameUtente);
            return params;
        
    ;

    RegisterRequest.getmInstance(getActivity()).addToRequestque(stringRequest);






这是适配器:

public class CespiteAdapter extends RecyclerView.Adapter<CespiteAdapter.ViewHolder>



private List<CespiteOgg> cespiteOggList;
private Context context;

public CespiteAdapter(List<CespiteOgg> cespiteOggList, Context context) 

    this.cespiteOggList = cespiteOggList;
    this.context = context;


public class ViewHolder extends RecyclerView.ViewHolder


    public CardView cv;
    public TextView txtNumInventario;
    public TextView txtNomeCespite;
    public TextView txtDtCatalogazione;
    public TextView txtAula;
    public TextView txtNomeUser;


    ViewHolder(View itemView)
    

        super (itemView);
        //cv = (CardView) itemView.findViewById(R.id.cardView);
        txtNumInventario = (TextView) itemView.findViewById(R.id.txtNumeroInventario);
        txtNomeCespite = (TextView) itemView.findViewById(R.id.txtNomeCespite);
        txtDtCatalogazione = (TextView) itemView.findViewById(R.id.txtDataCatalogazione);
        txtAula = (TextView) itemView.findViewById(R.id.txtAula);
        txtNomeUser= (TextView) itemView.findViewById(R.id.txtNomeUser);


    

【问题讨论】:

如果您从服务器获取数据,然后检查回收站视图项目大小,您可以检查来自 volley 的数据大小,if(array.length>0)//表示您有数据所以回收站视图不为空 【参考方案1】:

将此部分添加到您的适配器:

@Override
public int getItemCount() 
    return cespiteOggList.size();

你可以通过以下方式获得recyclerView的大小:

adapter.getItemCount()

【讨论】:

【参考方案2】:

您可以覆盖适配器 getItemCount (getItemCount()) 以返回列表的大小并从 RecyclerView(getAdapter()) 中获取适配器。

【讨论】:

【参考方案3】:

您可能需要覆盖onCreateViewHolderonBindViewHoldergetItemCountgetItemCount 返回的值等于 RecyclerView 的项目数。

【讨论】:

【参考方案4】:

你可以使用getitemcount

if (adapter.getItemCount() == 0)

    Toast.makeText(getApplicationContext(), "NO Data Found",Toast.LENGTH_SHORT).show();

【讨论】:

以上是关于如何检查 Recyclerview 是不是为空的主要内容,如果未能解决你的问题,请参考以下文章

如果为空,如何隐藏 Firestore RecyclerView

如何检查数据读取器是不是为空或为空

如何检查对象是不是为空

如何检查火花数据框是不是为空?

如何检查火花数据框是不是为空?

如何检查结果集是不是为空?