如何在RecycleView中使用FirebaseRecyclerAdaptor,即在RecycleView中列出Firebase数据

时间:2017-08-16 15:50:24

标签: android firebase firebase-realtime-database android-recyclerview firebaseui

它显示了我们如何使用FirebaseRecyclerAdaptar显示从firebase到回收站视图的数据列表。

输出

我们的输出如下所示,答案如下

enter image description here

1 个答案:

答案 0 :(得分:1)

我是Android的新手,我浪费了4天多的时间来做这件事。所以我正在解释这个解决方案,这样你就不必浪费时间了。

要求

  • 首先,您的项目应该连接到firebase。
  • 依赖关系
    • 编译com.google.firebase:firebase-database:11.0.0'
    • 编译' com.google.firebase:firebase-auth:11.0.0'
    • compile' com.android.support:recyclerview-v7:25.2.0'
    • 编译' com.firebaseui:firebase-ui-database:0.5.1'
    • 编译com.google.firebase:firebase-storage:10.0(如果您需要图片和其他存储文件)
    • compile' com.github.bumptech.glide:glide:4.0.0' (这是从数据库中显示图像)

我的Firebase数据库

enter image description here

我将使用FirebaseRecyclerAdaptar检索此数据并将其加载到RecycleView

从firebase获取和设置数据的模型

首先创建model.java文件,其中包含我们需要的所有数据的getter和setter以及构造函数。请注意,您在模式内定义的变量应与数据库字段的名称匹配。这是我的model.java文件,我将我的模型命名为Main.java,你可以自己命名。

public class Main implements Serializable {

    private String firstName;
    private String lastName;
    private String profilePic;
    private String email;
    private String id;
    private String phone;
    private String mobile;

    public Main(){

    }

    public Main(String firstName, String lastName, String profilePic, String email, String id, String phone, String mobile) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.profilePic = profilePic;
       this.email = email;
       this.id = id;
       this.phone = phone;
       this.mobile = mobile;
    }

    public String getMobile() {
       return mobile;
    }

    public void setMobile(String mobile) {
       this.mobile = mobile;
    }

    public String getPhone() {
       return phone;
    }

    public void setPhone(String phone) {
       this.phone = phone;
    }

    public String getId() {
       return id;
    }

    public void setId(String id) {
       this.id = id;
    }

    public String getFirstName() {
       return firstName;
    }

    public void setFirstName(String firstName) {
       this.firstName = firstName;
    }

    public String getLastName() {
       return lastName;
    }

    public void setLastName(String lastName) {
       this.lastName = lastName;
    }

    public String getProfilePic() {
       return profilePic;
    }

    public void setProfilePic(String profilePic) {
       this.profilePic = profilePic;
    }

    public String getEmail() {
       return email;
    }

    public void setEmail(String email) {
       this.email = email;
    }
}

您可以看到字符串名称,电子邮件与数据库字段名称,电子邮件完全相同。并且不要忘记创建空构造函数,因为firebase需要一个空构造函数。这里我已经定义了String中的所有变量,在你的情况下你也可以定义整数但是记住你的数据库应该包含整数值。

包含recyclerview

的主视图

现在创建一个包含recyclerView的视图。我已将我的视图创建为activity_main.xml,您可以自己命名。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.firebase.firebaseemailauthentication.Main2Activity"
   tools:showIn="@layout/app_bar_main2"
   android:orientation="vertical"
   >

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

</LinearLayout>

我的观点看起来像这样

mainview containing recyclier view

包含单行

的视图

现在你应该创建一个可以显示数据的新xml文件,即我创建的单行设计下面的row_profile_list.xml是xml文件的代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/mainLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:elevation="5dp"
   android:orientation="vertical"
   android:visibility="visible"
   app:cardBackgroundColor="#ffffff"
   app:cardCornerRadius="10dp"
   app:cardUseCompatPadding="true">

<LinearLayout
    android:id="@+id/row_profile_lists"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp"
    android:visibility="visible"
    android:weightSum="4">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.5"
        android:orientation="horizontal">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/row_profile_image"
            android:layout_width="wrap_content"
            android:layout_height="75dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:padding="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/row_fname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/row_lname"
                android:text="First Name"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/row_lname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_above="@+id/tf_email"
                android:gravity="left"
                android:paddingLeft="5sp"
                android:text="Last Name"
                android:textSize="16sp"
                android:textStyle="bold" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/row_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView"
                android:textSize="12sp" />
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1.5"
        android:orientation="horizontal">

        <Button
            android:id="@+id/row_call"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:layout_weight="1"
            android:text="Call" />
    </LinearLayout>


   </LinearLayout>
</LinearLayout>

此视图如下所示,您可以根据需要进行设计。

single row view design

现在让我们从FirebaseRecyclerAdaptar开始

创建一个返回activity_main.xml的Activity。在主要活动内部定义了回收器视图和firebase recycleler adaptar,如下所示

private RecyclerView recycler_profile_lists;
private FirebaseRecyclerAdapter adapter;

比如在这样的方法中使用recycleview分配recycleler_profile_lists

recycler_profile_lists = (RecyclerView) findViewById(R.id.recycle_profile_list);
fetchProfileLists();

请注意,findViewById(R.id.recycle_profile_list)是在activity_main.xml中设计的RecyclerView的id。 fetchProfileLists()引用另一个方法或函数。我这样做是因为我不想在create方法中做所有内容。你也最好不要在onCreate方法中做。

现在你应该做的另一件事是制作ViewHolder方法,该方法包含我们之前创建的单行视图,即row_profile_list.xml。 View holder类看起来像这样。我把它命名为ProfileListHolder。这里它扩展了RecyclerView.ViewHolder,它有助于保持特定的视图。 我们已经定义了一些视图,文本视图,图像视图和按钮。然后你可以看到我们在上面定义的视图中分配了itemView的mView = itemView。和其他textview和图像视图也是具有相应视图的分配器。请注意,您在此处指定的ID应在单行视图中定义,即row_profile_list.xml

public static class ProfileListHolder extends RecyclerView.ViewHolder {
    public View mainLayout;
    public View linearLayout;
    View mView;
    public Main my = new Main();
    TextView firstName;
    TextView lastName;
    TextView email;
    ImageView profilePic;
    Button phoneCall;

    View view;

    public ProfileListHolder(final View itemView) {
        super(itemView);
        mView = itemView;

        firstName = (TextView) itemView.findViewById(R.id.row_fname);
        lastName = (TextView) itemView.findViewById(R.id.row_lname);
        email = (TextView) itemView.findViewById(R.id.row_email);
        profilePic = (ImageView) itemView.findViewById(R.id.row_profile_image);
        phoneCall = (Button) itemView.findViewById(R.id.row_call);
        mainLayout = itemView.findViewById(R.id.mainLayout);
        linearLayout = itemView.findViewById(R.id.row_profile_lists);





        view = itemView.findViewById(R.id.row_profile_lists);
    }
}

现在fetchProfileLists方法或函数看起来像这样。

private void fetchProfileLists() {
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    recycler_profile_lists.setHasFixedSize(true);
    recycler_profile_lists.setLayoutManager(new LinearLayoutManager(this));

    adapter = new FirebaseRecyclerAdapter<Main, ProfileListHolder>(Main.class, R.layout.row_profile_list, ProfileListHolder.class, ref.child("userProfile")) {
        @Override
        protected void populateViewHolder(final ProfileListHolder viewHolder, final Main model, final int position) {
            String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
            if (!userid.matches(model.getId())) {
                viewHolder.mainLayout.setVisibility(View.VISIBLE);
                viewHolder.linearLayout.setVisibility(View.VISIBLE);
                viewHolder.firstName.setText(model.getFirstName());
                viewHolder.lastName.setText(model.getLastName());
                viewHolder.email.setText(model.getEmail());

                Glide.with(Main2Activity.this).load(model.getProfilePic())
                        .thumbnail(0.5f)
                        .into(viewHolder.profilePic);

                viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String id = model.getId();
                        Intent i=new Intent(Main2Activity.this, OtherProfileActivity.class);
                        i.putExtra("user_id",id);
                        startActivity(i);
                    }
                });

                viewHolder.phoneCall.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {




                        final String phone = model.getPhone();
                        final String mobile = model.getMobile();
                        if(!TextUtils.isEmpty(mobile)){

                            LayoutInflater inflater = Main2Activity.this.getLayoutInflater();
                            final View view = inflater.inflate(R.layout.alert_dialog, null);

                            TextView alert_mobile = (TextView) view.findViewById(R.id.alert_mobile);
                            alert_mobile.setText(mobile);

                            TextView alert_phone = (TextView) view.findViewById(R.id.alert_phone);
                            alert_phone.setText(phone);

                            Button alert_call_phone = (Button) view.findViewById(R.id.alert_phone_btn);
                            alert_call_phone.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent call = new Intent(Intent.ACTION_DIAL);
                                    call.setData(Uri.parse("tel:" + phone));
                                    startActivity(call);
                                }
                            });

                            Button alert_call_mobile = (Button) view.findViewById(R.id.alert_mobile_btn);
                            alert_call_mobile.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent call = new Intent(Intent.ACTION_DIAL);
                                    call.setData(Uri.parse("tel:" + mobile));
                                    startActivity(call);
                                }
                            });

                            Button alert_cancel = (Button) view.findViewById(R.id.alert_cancel_btn);
                            alert_cancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Main2Activity.this.alertDialog.dismiss();
                                }
                            });

                            AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
                            builder.setView(view);
                            Main2Activity.this.alertDialog = builder.create();
                            Main2Activity.this.alertDialog.show();

                        }else{
                            Intent call = new Intent(Intent.ACTION_DIAL);
                            call.setData(Uri.parse("tel:" + phone));
                            startActivity(call);
                        }


                    }
                });
            }else{
                int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 0, getResources().getDisplayMetrics());
                viewHolder.mainLayout.setMinimumHeight(px);
            }

        }


    };


    recycler_profile_lists.setAdapter(adapter);
}

现在我将详细解释FirebaseRecyclerAdaptar 首先我们参考了我们的数据库,我们为RecyclerView设置了大小和布局管理器。这是因为我们希望以线性方式显示我们的内容。我们也可以在Grid布局中显示我们的RecyclerView。 现在我们已经在之前定义的adaptar中配置了新的FirebaseRecyclerAdaptar。在这里我们已经通过&lt; Main,ProfileListHolder&gt;像这样,Main指的是Main.java,它是我们之前创建的模型。和ProfileListHolder是我们上面创建的视图持有者。现在我们可以传递四个不同的参数。第一个是模型类,第二个是单个布局,即R.layout.row_profile_list,请注意我们没有在视图持有者中定义此布局。感觉这个单行视图将由我们的视图持有者持有。另一个参数是viewholder类,最后一个参数是数据库引用。请注意,给定的数据库引用应包含数组而不是对象。如果您的数据库引用保持对象比这将抛出错误。现在在填充视图中我们有三个参数,第一个是视图持有者,第二个是模型,第三个是位置。现在你可以看到viewHolder.firstName.setText(model.getName());这样做是表单viewHolder我们可以访问我们创建和分配的视图。在该视图中,我们可以使用mode.getName(); model.getName()将从具有相应位置的数据库返回值,并将填充视图。对于每个数据,它将填充新视图。 您可以在填充视图中为项目和项目的其他textview或按钮设置onClickListener。 如果您有任何疑问,可以随时询问。

相关问题