不知道如何完成Firebase RecyclerAdapter

时间:2018-09-05 09:39:29

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

我一直想弄清楚如何使Firebase RecyclerAdapter正常工作,但一直无法解决这一问题。 我在Stack Overflow上阅读了很多线程,但无法弄清楚。

我还没有完成onBindViewHolder,但是onCreateViewHolder也不起作用。 “父母”一词始终为红色。

问题出在AllUserActivitys.java文件中,我还提供了其余的代码。

这是我的代码:

AllUsersActivity.java:

package com.example.android.whammychat;

import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class AllUsersActivity extends AppCompatActivity {

    private Toolbar mAllUsersToolBar;
    private RecyclerView mAllUsersRecyclerView;
    private DatabaseReference mAllUsersDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_users);

        mAllUsersToolBar = findViewById(R.id.allUsersToolBar);
        setSupportActionBar(mAllUsersToolBar);
        getSupportActionBar().setTitle("All Users");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mAllUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");

        mAllUsersRecyclerView = findViewById(R.id.allUsersRecyclerView);
        mAllUsersRecyclerView.setHasFixedSize(true);
        mAllUsersRecyclerView.setLayoutManager(new LinearLayoutManager(this));



    }

    //We are putting this in .onStart because we want to retrieve the data in real time.
    @Override
    protected void onStart() {
        super.onStart();


        FirebaseRecyclerOptions<Users> options =
                new FirebaseRecyclerOptions.Builder<Users>()
                        .setQuery(mAllUsersDatabase, Users.class)
                        .build();


        FirebaseRecyclerAdapter firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.individual_user, parent, false);

                return new UsersViewHolder(view);

            }

            @Override
            protected void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull Object model) {

            }

        };


    }


    public class UsersViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public UsersViewHolder(@NonNull View itemView) {
            super(itemView);

            /*
           itemView is a single row in the ListView.
           We are going to be using mView later to perform an onClickListener method on the ViewHolder.
             */
            mView = itemView;

        }
    }

}

Users.java:

package com.example.android.whammychat;

public class Users {

    public String username;
    public String status;
    public String image;

    //Constructor without parameters is also needed because: https://stackoverflow.com/questions/18993936/how-to-best-explain-and-use-empty-constructors-in-java
    public Users() {

    }

    public Users(String username, String status, String image) {
        this.username = username;
        this.status = status;
        this.image = image;
    }

    //Getters
    public String getUsername() {
        return username;
    }

    public String getStatus() {
        return status;
    }

    public String getImage() {
        return image;
    }


}

activity_all_users:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".AllUsersActivity">

    <include
        android:id="@+id/allUsersToolBar"
        layout="@layout/app_bar"/>

    <view
        android:id="@+id/allUsersRecyclerView"
        class="android.support.v7.app.AlertController$RecycleListView"
        android:layout_width="match_parent"
        android:layout_height="512dp"
        android:layout_marginTop="56dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </view>

</android.support.constraint.ConstraintLayout>

individual_user.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="139dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/individualUserPictureImageView"
            android:layout_width="105dp"
            android:layout_height="100dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:src="@drawable/profile_pic"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/individualUserStatusTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="24dp"
            android:layout_marginTop="12dp"
            android:text="TextView"
            android:textSize="18sp"
            app:layout_constraintStart_toEndOf="@+id/individualUserPictureImageView"
            app:layout_constraintTop_toBottomOf="@+id/individualUserNameTextView" />

        <TextView
            android:id="@+id/individualUserNameTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/individualUserStatusTextView"
            android:layout_marginStart="24dp"
            android:layout_marginTop="28dp"
            android:text="TextView"
            android:textColor="@android:color/black"
            android:textSize="24sp"
            android:textStyle="bold"
            app:layout_constraintStart_toEndOf="@+id/individualUserPictureImageView"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>


</android.support.constraint.ConstraintLayout>

编辑: 现在,AllUsersActivity.java文件部分中的“ RecyclerView.ViewHolder”用红色下划线标出,因为它表示FirebaseRecyclerAdapter与android.support.v7.widget.RecyclerView.adapter发生冲突。我尝试删除导入android.support.v7.widget.RecyclerView;从AllUsersActivity.java文件中获取,但它会继续自动返回。我该怎么办?

3 个答案:

答案 0 :(得分:0)

问题出在您的onCreateViewHolder

替换:

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.individual_user, parent, false);

    return new UsersViewHolder(view);

}

使用:

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.individual_user, viewGroup, false);
    return new UsersViewHolder(view);

}

答案 1 :(得分:0)

要解决此问题,只需更改以下代码行:

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

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

在您的代码中,partent视图组是viewGroup对象的一个​​onCreateViewHolder()对象。

如果您有兴趣,建议使用 this ,您可以从Firebase Realtime数据库中检索数据并使用{{1}在RecyclerView中显示数据}。

答案 2 :(得分:0)

此代码正在运行。 AllUsersActivity

public class AllUsersActivity extends AppCompatActivity {

    private Toolbar mAllUsersToolBar;
    private RecyclerView mAllUsersRecyclerView;
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseUsersAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_users);

        mAllUsersToolBar = findViewById(R.id.allUsersToolBar);
        setSupportActionBar(mAllUsersToolBar);
        getSupportActionBar().setTitle("All Users");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mAllUsersRecyclerView = findViewById(R.id.allUsersRecyclerView);

        Query query = FirebaseDatabase.getInstance().getReference().child("Users"); // you can add child as .child("child_name");

        FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
                .setQuery(query, Users.class)
                .build();

         firebaseUsersAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
                options) {
            @Override
            protected void onBindViewHolder(UsersViewHolder holder, int position, Users model) {
                holder.mIndividualUserName.setText(model.getUsername());
                holder.mIndividualUserStatus.setText(model.getStatus());
                holder.mIndividualUserPicture.setImageDrawable(getDrawable(R.drawable.profile_pic));
            }

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

        mAllUsersRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAllUsersRecyclerView.setAdapter(firebaseUsersAdapter);
        firebaseUsersAdapter.startListening();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(firebaseUsersAdapter != null){
            firebaseUsersAdapter.startListening();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(firebaseUsersAdapter != null){
            firebaseUsersAdapter.stopListening();
        }
    }
}

UsersViewHolder 我从活动中提取了该类,这将帮助您获得更好的代码。

public class UsersViewHolder extends RecyclerView.ViewHolder {

    protected ImageView mIndividualUserPicture;
    protected TextView mIndividualUserName;
    protected TextView mIndividualUserStatus;


    public UsersViewHolder(@NonNull View itemView) {
        super(itemView);

        mIndividualUserPicture = itemView.findViewById(R.id.individualUserPictureImageView);
        mIndividualUserName = itemView.findViewById(R.id.individualUserNameTextView);
        mIndividualUserStatus = itemView.findViewById(R.id.individualUserStatusTextView);


    }
}

我也对个人用户布局进行了一些更改:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="139dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/individualUserPictureImageView"
            android:layout_width="105dp"
            android:layout_height="100dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:src="@drawable/profile_pic"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/individualUserStatusTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="24dp"
            android:layout_marginTop="12dp"
            android:text="TextView"
            android:textSize="18sp"
            app:layout_constraintStart_toEndOf="@+id/individualUserPictureImageView"
            app:layout_constraintTop_toBottomOf="@+id/individualUserNameTextView" />

        <TextView
            android:id="@+id/individualUserNameTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/individualUserStatusTextView"
            android:layout_marginStart="24dp"
            android:layout_marginTop="28dp"
            android:text="TextView"
            android:textColor="@android:color/black"
            android:textSize="24sp"
            android:textStyle="bold"
            app:layout_constraintStart_toEndOf="@+id/individualUserPictureImageView"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>


</android.support.constraint.ConstraintLayout>

我测试了此代码,应用程序按预期运行。

应用程序: enter image description here

如果您还有其他需要,可以在我的电子邮件地址中向我发送一条消息,并将其保存在数据库中;)