如何在片段中使用FirebaseRecycle适配器显示Firebase数据库?

时间:2018-11-04 07:35:04

标签: android firebase firebase-realtime-database

我是Android的初学者。

能否请您指导我如何在片段中显示Firebase数据?

1 个答案:

答案 0 :(得分:1)

示例如何使用FirebaseRecyclerAdpater:
来源https://medium.com/android-grid/how-to-use-firebaserecycleradpater-with-latest-firebase-dependencies-in-android-aff7a33adb8b

实施Firebase Realtime数据库后 创建一个Model类,并在其中复制以下代码,或者使用您自己的代码。

package example.androidgrid.firebaserecycleradapter;

public class Model {
public String mId, mTitle, mDesc;

public Model() {

}

public Model(String mId, String mTitle, String mDesc) {
    this.mId = mId;
    this.mTitle = mTitle;
    this.mDesc = mDesc;
}

public String getmId() {
    return mId;
}

public void setmId(String mId) {
    this.mId = mId;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmDesc() {
    return mDesc;
}

public void setmDesc(String mDesc) {
    this.mDesc = mDesc;
}

}

创建一个list_item.xml布局。我们将其用作列表项。

   <?xml version="1.0" encoding="utf-8"?>
  <android.support.v7.widget.CardView 
 xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp">

<LinearLayout
    android:id="@+id/list_root"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="true"
    android:orientation="vertical"
    android:background="?attr/selectableItemBackground"
    android:padding="16dp">

    <TextView
        android:id="@+id/list_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/list_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="Description" />

</LinearLayout>

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

打开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"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:layout_gravity="center" />
    <EditText
        android:id="@+id/etd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:layout_gravity="center" />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add"/>
</LinearLayout>

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

现在,我们要编写一些重要的代码。打开MainActivity.java并添加这些变量。

private EditText editText, etd;
private Button button;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private FirebaseRecyclerAdapter adapter;

现在在onCreate()方法中声明视图

editText = findViewById(R.id.et);
etd = findViewById(R.id.etd);
button = findViewById(R.id.btn);
recyclerView = findViewById(R.id.list);

要在列表中显示数据,我们需要一些数据存在数据库中,因此我们将通过此方法添加数据

button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
          DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("posts").push();
          Map<String, Object> map = new HashMap<>();
          map.put("id", databaseReference.getKey());
          map.put("title", editText.getText().toString());
          map.put("desc", etd.getText().toString());

          databaseReference.setValue(map);

      }
});

设置RecyclerView

linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
fetch();

现在,我们需要一个ViewHolder来处理每个位置的视图。

public class ViewHolder extends RecyclerView.ViewHolder {
    public LinearLayout root;
    public TextView txtTitle;
    public TextView txtDesc;

    public ViewHolder(View itemView) {
        super(itemView);
        root = itemView.findViewById(R.id.list_root);
        txtTitle = itemView.findViewById(R.id.list_title);
        txtDesc = itemView.findViewById(R.id.list_desc);
    }

    public void setTxtTitle(String string) {
        txtTitle.setText(string);
    }


    public void setTxtDesc(String string) {
        txtDesc.setText(string);
    }
}

现在,我们将从数据库中获取数据

 private void fetch() {
        Query query = FirebaseDatabase.getInstance()
                .getReference()
                .child("posts");

        FirebaseRecyclerOptions<Model> options =
                new FirebaseRecyclerOptions.Builder<Model>()
                        .setQuery(query, new SnapshotParser<Model>() {
                            @NonNull
                            @Override
                            public Model parseSnapshot(@NonNull DataSnapshot snapshot) {
                                return new Model(snapshot.child("id").getValue().toString(),
                                        snapshot.child("title").getValue().toString(),
                                        snapshot.child("desc").getValue().toString());
                            }
                        })
                        .build();

        adapter = new FirebaseRecyclerAdapter<Model, ViewHolder>(options) {
            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.list_item, parent, false);

                return new ViewHolder(view);
            }


            @Override
            protected void onBindViewHolder(ViewHolder holder, final int position, Model model) {
                holder.setTxtTitle(model.getmTitle());
                holder.setTxtDesc(model.getmDesc());

                holder.root.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
                    }
                });
            }

        };
        recyclerView.setAdapter(adapter);
}

如果您运行该应用程序,它将不会显示任何数据,因为我们必须添加以下侦听器

@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}