Firebase for android : Read list of data from database and show on recyclerview

Firebase for android : Read list of data from database and show on recyclerview

Part -1 :
Take that we have some data field on child node named “user” . We will first retrieve all data and then we will show it on recyclerview. ,

public class UserListActivity extends AppCompatActivity {
    private DatabaseReference mDatabase;

  
    ArrayList<User> userArrayList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
       
       




        mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child("user").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                 Toast.makeText(UserListActivity.this, snapshot.toString(), Toast.LENGTH_SHORT).show();

 
 @Override
 public void onCancelled(DatabaseError databaseError) {
 System.out.print(databaseError.toString());
 }


 });




 }

}

Part 2 :

So got the data from firebase of child named “user” . Now we will show it on recyclerview . I have just pasting code of class and layout files .

Part 2a : UserList class  

 public class UserListActivity extends AppCompatActivity {
 private DatabaseReference mDatabase;

private RecyclerView mRecyclerView;
 private UserListAdapter mAdapter;
 private RecyclerView.LayoutManager mLayoutManager;

ArrayList<User> userArrayList;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_user_list);
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);
 getSupportActionBar().setTitle("Add Friend");

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
 getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
 }

mRecyclerView = (RecyclerView) findViewById(R.id.user_recycler);
 mRecyclerView.setHasFixedSize(true);
 mLayoutManager = new LinearLayoutManager(this);
 mRecyclerView.setLayoutManager(mLayoutManager);

mDatabase = FirebaseDatabase.getInstance().getReference();

 mDatabase.child("user").addValueEventListener(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot snapshot) {

userArrayList = new ArrayList<User>();
 for (DataSnapshot postSnapshot: snapshot.getChildren()) {

User user = postSnapshot.getValue(User.class);
 User users = new User();
 users.name = user.name;
 users.avata = user.avata;

userArrayList.add(users);
 }
 Collections.reverse(userArrayList);
 mAdapter = new UserListAdapter(userArrayList);
 mRecyclerView.setAdapter(mAdapter);
 mRecyclerView.invalidate();

}

@Override
 public void onCancelled(DatabaseError databaseError) {
 System.out.print(databaseError.toString());
 }

});

}

}

 

Part 2b – UserList layout :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.adndigital.priokotha.activities.addFriend.UserListActivity"
    tools:showIn="@layout/activity_user_list">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/user_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>




</RelativeLayout>

Part 2c : Adapter class :

public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.UserListViewHolder>{

    Context context;
    ArrayList<User> userArrayList;
    LovelyProgressDialog dialogWait;
    public UserListAdapter(ArrayList<User> userArrayList) {
        this.userArrayList = userArrayList;
    }

    @Override
    public UserListAdapter.UserListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        dialogWait = new LovelyProgressDialog(context);

        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.user_list_adapter, parent, false);

        UserListViewHolder itemFriendViewHolder = new UserListViewHolder(view);
        return itemFriendViewHolder;
    }

    @Override
    public void onBindViewHolder(UserListAdapter.UserListViewHolder holder, int position) {


        Picasso.with(context)
                .load(userArrayList.get(position).avata)
                .placeholder(R.drawable.default_avata)
                .error(R.drawable.default_avata)
                .into(holder.avata);



        String user =userArrayList.get(position).name;
        String userName = user.split("\\.")[0];
       // String extension = textfile.split("\\.")[1];



        holder.name.setText(userName);
        holder.addFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new LovelyTextInputDialog(context, R.style.EditTextTintTheme)
                        .setTopColorRes(R.color.colorPrimary)
                        .setTitle("Add friend")
                        .setMessage("Enter friend email")
                        .setIcon(R.drawable.ic_add_friend)
                        .setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS)
                        .setInputFilter("Email not found", new LovelyTextInputDialog.TextFilter() {
                            @Override
                            public boolean check(String text) {
                                Pattern VALID_EMAIL_ADDRESS_REGEX =
                                        Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
                                Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(text);
                                return matcher.find();
                            }
                        })
                        .setConfirmButton(android.R.string.ok, new LovelyTextInputDialog.OnTextInputConfirmListener() {
                            @Override
                            public void onTextInputConfirmed(String text) {

                                findIDEmail(text);

                            }
                        })
                        .show();



            }
        });
    }




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

    public class UserListViewHolder extends RecyclerView.ViewHolder {


        ImageView avata;
        TextView name;
        Button addFriend;
        public UserListViewHolder(View itemView) {
            super(itemView);

            avata = itemView.findViewById(R.id.icon_avata);
            name = itemView.findViewById(R.id.name);
            addFriend = itemView.findViewById(R.id.add_friend);
        }
    }








}
}

 

 

Part 2d : adapter layout 

 

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_marginBottom="5dp"
    android:layout_marginTop="5dp"
    android:layout_marginStart="5dp"
    android:layout_marginEnd="5dp"
    card_view:cardBackgroundColor="@color/colorCardView"
    card_view:cardCornerRadius="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
       >

        <de.hdodenhof.circleimageview.CircleImageView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/icon_avata"
            android:src="@drawable/default_avata"
            android:layout_width="60dp"
            android:layout_height="60dp"
            app:civ_border_color="@color/colorPrimary"/>


        <LinearLayout
            android:orientation="horizontal"
            android:weightSum="2"
            android:layout_gravity="center"
            android:gravity="center"

            android:layout_marginLeft="10dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/name"
                android:layout_weight="1"
                android:text=""
                android:textColor="@color/facebook_color"
                android:textSize="@dimen/count_14dp"
                android:maxLines="4"
                android:lines="4"
                android:gravity="center_vertical"
                android:layout_marginRight="10dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <Button
                android:id="@+id/add_friend"
                android:layout_weight="1"
                android:text="ADD FRIEND"

                android:drawableLeft="@drawable/add_friend"
                android:textColor="#FFFFFF"
                android:background="#3B5998"

                android:padding="@dimen/count_5dp"
                android:layout_width="match_parent"
                android:layout_height="40dp" />




        </LinearLayout>







        <!--<LinearLayout-->
            <!--android:layout_width="0dp"-->
            <!--android:layout_height="match_parent"-->
            <!--android:layout_marginStart="10dp"-->
            <!--android:layout_weight="5"-->
            <!--android:orientation="vertical">-->

            <!--<LinearLayout-->
                <!--android:layout_width="match_parent"-->
                <!--android:layout_height="0dp"-->
                <!--android:layout_gravity=""-->
                <!--android:layout_weight="1"-->
                <!--android:layout_marginRight="10dp"-->
                <!--android:orientation="horizontal"-->
              <!--&gt;-->

                <!--<TextView-->
                    <!--android:text="sdfdsfsdfsdfsd"-->
                    <!--android:id="@+id/txtName"-->
                    <!--android:layout_width="0dp"-->
                    <!--android:layout_height="match_parent"-->
                    <!--android:layout_weight="4"-->
                    <!--android:maxLines="4"-->

                    <!--android:layout_gravity="center"-->
                    <!--android:textColor="#3498DB"-->
                    <!--android:lines="4"-->
                    <!--android:gravity="center_vertical"-->
                    <!--android:textAppearance="?android:attr/textAppearanceMedium" />-->


                <!--<Button-->
                    <!--android:text="sdfsdfsdfsdfsd"-->
                    <!--android:padding="10dp"-->
                    <!--android:layout_marginRight="10dp"-->
                    <!--android:background="@color/facebook_color"-->
                    <!--android:layout_gravity="center"-->
                    <!--android:layout_width="match_parent"-->
                    <!--android:layout_height="wrap_content" />-->
               <!---->
            <!--</LinearLayout>-->

           <!---->
        <!--</LinearLayout>-->
    </LinearLayout>
</android.support.v7.widget.CardView>

 

 

Part 2e : Model class 

 

public class User {
   
    public String name;
    public String avata;
   


   
}

Leave a Reply

Your email address will not be published. Required fields are marked *