How to display textview if recyclerview empty android

Viewed 1723

I try to display textview if recyclerview empty.I get data from database and display in recyclerview . but some times I do not have data in database so I want display textview if no data. For a long time I try most of answers I found it posted here but all not working with me.I don't Know what is problem. If anyone know solution please help me.

public class ViewCom extends Fragment {

    private TextView emptyView;
    private List<List_Data> list_data;
    private RecyclerView rvcy;
    private MyAdapter adapter;
    CardView cardView;
    private static final String TAG = "ViewCom";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        View rootView = inflater.inflate(R.layout.fragment_comment, container, false);

cardView=(CardView)rootView.findViewById(R.id.cardView);
        emptyView = (TextView) rootView.findViewById(R.id.empty_view);

        Intent i = getActivity().getIntent();
        final String mid = i.getStringExtra("mid");
        rvcy=(RecyclerView)rootView.findViewById(R.id.recyclerview);
        rvcy.setHasFixedSize(true);
        rvcy.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
        list_data=new ArrayList<>();
        adapter=new MyAdapter(list_data);
        getComment(mid);
        rvcy.setAdapter(adapter);
        return rootView;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

private void getComment(String mid){

    final String HI ="http://===========/Sh.php?mid=" + mid ;
    StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject=new JSONObject(response);
                JSONArray array=jsonObject.getJSONArray("data");

                for (int i=0; i<array.length(); i++ ) {
                    JSONObject ob = array.getJSONObject(i);
                    List_Data listData = new List_Data(ob.getString("comment")
                            , ob.getString("name"));
                    list_data.add(listData);

                    adapter.notifyDataSetChanged();
                    Log.i(TAG, "test2"+array.toString());

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

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

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
    requestQueue.add(stringRequest);

}


}



public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
    private List<List_Data>list_data;
    public MyAdapter(List<List_Data> list_data) {
        this.list_data = list_data;

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_data,parent,false);
        return new ViewHolder(view);

    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        List_Data listData=list_data.get(position);
        holder.txtname.setText(listData.gettext());
        holder.txtm.setText(listData.getmid());

    }

    @Override
    public int getItemCount() {
        return list_data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView txtname,txtm,ImageView;
        public ViewHolder(View itemView) {
            super(itemView);
            txtname=(TextView)itemView.findViewById(R.id.txt_name);
            txtm=(TextView)itemView.findViewById(R.id.txt_mname);
        }
    }

}

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <androidx.cardview.widget.CardView
                android:id="@+id/cardView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:layout_gravity="center"
                android:layout_marginStart="20dp"
                android:layout_marginLeft="20dp"
                android:layout_marginEnd="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginBottom="20dp"
                android:elevation="5dp"
                app:cardCornerRadius="@dimen/loginCardRadiuss">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/empty_view"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:gravity="center"
                        android:text="no_data_available"
                        android:visibility="gone" />

                    <androidx.recyclerview.widget.RecyclerView
                        android:id="@+id/recyclerview"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                    </androidx.recyclerview.widget.RecyclerView>
                </LinearLayout>

            </androidx.cardview.widget.CardView>

4 Answers

Try this

for (int i=0; i<array.length(); i++ ) {
    JSONObject ob = array.getJSONObject(i);
    List_Data listData = new List_Data(ob.getString("comment")
            , ob.getString("name"));
    list_data.add(listData);

    Log.i(TAG, "test2"+array.toString());

}
adapter.notifyDataSetChanged();
rvcy.setVisibility(list_data.isEmpty() ? View.GONE : View.VISIBLE)
emptyView.setVisibility(list_data.isEmpty() ? View.VISIBLE : View.GONE)

You have to check the response ArrayList is empty or not. if your ArrayList is empty then gone the recycler view visibility and visible the textView.

update your code with below code:-

private void getComment(String mid){

    final String HI ="http://===========/Sh.php?mid=" + mid ;
    StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject=new JSONObject(response);
                JSONArray array=jsonObject.getJSONArray("data");

                for (int i=0; i<array.length(); i++ ) {
                    JSONObject ob = array.getJSONObject(i);
                    List_Data listData = new List_Data(ob.getString("comment")
                            , ob.getString("name"));
                    list_data.add(listData);
                    Log.i(TAG, "test2"+array.toString());
                }
                 rvcy.setVisibility(list_data.size() > 0 ? View.VISIBLE : View.GONE) // here check check your arraylist size if it greater then zero then textView is hide and recyclerview show.
                 emptyView.setVisibility(list_data.size() > 0 ? View.GONE : View.VISIBLE) //same condition for text view if list_data size greater then zero then it'll Hide. otherwise it'll display
                 adapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
              rvcy.setVisibility(list_data.size() > 0 ? View.VISIBLE : View.GONE) // here check check your arraylist size if it greater then zero then textView is hide and recyclerview show.
              emptyView.setVisibility(list_data.size() > 0 ? View.GONE : View.VISIBLE) //same condition for text view if list_data size greater then zero then it'll Hide. otherwise it'll display
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
    requestQueue.add(stringRequest);

}

Check if the JSON array is greater than 0, so that the RecyclerView will have some data.

try {
    JSONObject jsonObject=new JSONObject(response);
    JSONArray array=jsonObject.getJSONArray("data");

    if (array.length() > 0) {
        rvcy.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);
    } else {
        rvcy.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
    }

    for (int i=0; i<array.length(); i++ ) {
        JSONObject ob = array.getJSONObject(i);
        List_Data listData = new List_Data(ob.getString("comment")
                , ob.getString("name"));
        list_data.add(listData);

        adapter.notifyDataSetChanged();
        Log.i(TAG, "test2"+array.toString());

    }

} catch (JSONException e) {
    e.printStackTrace();
}

have you already thought of using Databinding? It is a good way to keep your code clearly.

I have written a toolkit library that may help you to understand it better. You can find some Databinding adapter here where you can Show/Hide views without any code.

Related