无法使用Firebase数据填充RecyclerView适配器

时间:2018-08-07 18:04:54

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

我正试图从Firebase数据库中获取数据,但由于某种原因它无法正常工作,因此我将尝试提供尽可能多的信息。.

这是数据库快照:

Database Users

这是一个POJO类:

public class Result2 implements Serializable {

private int score;
private String userName;

public Result2(int score, String userName) {
    this.score = score;
    this.userName = userName;
}

public int getScore() {
    return score;
}


public String getUserName() {
    return userName;
}

}

这是我的活动布局,称为activity_results.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:weightSum="2"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <TextView
        android:textColor="#000"
        android:textSize="16sp"
        android:gravity="center"
        android:text="USERNAME"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />

    <TextView
        android:textColor="#000"
        android:textSize="16sp"
        android:text="SCORE"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />

</LinearLayout>

<View
    android:background="#000"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    />

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="10dp"
    android:clipToPadding="false"
    android:scrollbars="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

如您所见,我想有2个TextViews(其作用类似于选项卡)和一个RecyclerView,其下将显示数据

这是我的Adapters ViewHolder布局,名为score_view_holder.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:weightSum="2">

    <TextView
        android:id="@+id/username"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/score"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:textSize="14sp" />


</LinearLayout>

<View
    android:background="#4545"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginEnd="10dp"
    android:layout_marginStart="10dp"/>

因此它将包含两个水平的TextViews和一个View作为下面的一行。

这是我的适配器:

public class ScoreAdapter extends RecyclerView.Adapter<ScoreAdapter.ScoreViewHolder> {

private List<Result2> results = new ArrayList<>();

public void setResults(List<Result2> results) {
    this.results.clear();
    this.results.addAll(results);
    notifyDataSetChanged();
}

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

@Override
public void onBindViewHolder(ScoreAdapter.ScoreViewHolder holder, int position) {
    Result2 result = getResult(position);
    if (result != null) {
        holder.setUsername(result.getUserName() != null ? result.getUserName() : "-");
        holder.setScore(String.valueOf(result.getScore()));
    }
}

private Result2 getResult(int position) {
    return !results.isEmpty() ? results.get(position) : null;
}

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

public class ScoreViewHolder extends RecyclerView.ViewHolder {

    private TextView username;
    private TextView score;

    public ScoreViewHolder(View itemView) {
        super(itemView);
        username = itemView.findViewById(R.id.username);
        score = itemView.findViewById(R.id.score);
    }

    public void setUsername(String username) {
        this.username.setText(username);
    }

    public void setScore(String score) {
        this.score.setText(score);
    }

}

}

它应该获取Result2对象的列表,并在这两个TextViews(用户名和得分)中设置文本

最后是我的活动,其中所有的魔力都没有发生:)

public class Results extends AppCompatActivity {

private DatabaseReference mDatabase;
private ScoreAdapter scoreAdapter;
private RecyclerView recyclerView;
private List<Result2> results = new ArrayList<>();


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

    recyclerView = findViewById(R.id.recycler_view);
    scoreAdapter = new ScoreAdapter();
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(scoreAdapter);

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

    loadResults();
}

private void loadResults() {

    mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                Result2 result =  childSnapshot.getValue(Result2.class);

                if(result != null) {
                    results.add(result);
                }
            }
            Toast.makeText(Results.this, String.valueOf(results.size()), Toast.LENGTH_SHORT).show();
            scoreAdapter.setResults(results);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
}

);
}
}

最有趣的是,Toast显示正确的结果数,但是当scoreAdapter.setResults(results);被调用,屏幕闪烁并返回到第一屏幕。它与POJO类,onDataChange方法或主线程有关吗?

我尝试了调试,并且在这里也很有趣。.这是ScoreAdapter setResult方法中的断点所捕获的内容:

ScoreAdapter setResult() method

我尝试在onBindViewHolder和getResults()中设置断点,但是没有一个被称为:o

1 个答案:

答案 0 :(得分:0)

if(result != null) {
     results.add(result);
}

请参阅此处,您正在检查result != null。但是result是类型为Results的引用变量。因此它不会为null,它将包含一些值。

因此,请尝试删除该if语句,并且仅执行-

results.add(result);