【问题标题】:Adding data in array list is failed在数组列表中添加数据失败
【发布时间】:2019-05-01 20:56:39
【问题描述】:

我想将一个名为 funny_momments_row 的对象添加到一个名为 dataArrayList 中,但它没有添加。我正在检查data 是否为空或之后没有使用isEmpty 方法。代码运行良好,直到这一行:

funny_momments_row current = new funny_momments_row(dataSnapshot.child("like").getValue().toString(),dataSnapshot.child("url").getValue().toString());

这是完整的类:

public class funny_moments extends Fragment {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("funnymomments");
    ArrayList<funny_momments_row> data;
    TextView tesgting;

    private RecyclerView mRecyclerView;

    public funny_moments() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_funny_moments, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recylerview);
        tesgting = (TextView) view.findViewById(R.id.test);
        data = new ArrayList<>();
        getData();

        // Inflate the layout for this fragment
        return view;
    }

    public void getData() {
        funny_momments_row lu = new funny_momments_row("1", "hi");
        myRef.child("video 0").setValue(lu);
        myRef.child("video 0").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot videoSnapshot: dataSnapshot.getChildren()) {
                    funny_momments_row current = new funny_momments_row(dataSnapshot.child("like").getValue().toString(), dataSnapshot.child("url").getValue().toString());
                    data.add(current);
                }
            }

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

            }
        });

        if (data.isEmpty()) {
            tesgting.setText("hi");
        }
    }
}

【问题讨论】:

  • 请在您的询问中添加您的例外情况。
  • 你检查过 OnDataChange() 调用和内部 for 循环执行了吗?
  • 如果应用程序崩溃,会有一个堆栈跟踪。请在 logcat 上查找,并将其添加到您的问题中。也请回复@。

标签: java android firebase arraylist firebase-realtime-database


【解决方案1】:

试试这个,因为videoSnapsot 是您需要添加到数组列表中的数据。

  public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot videoSnapshot: dataSnapshot.getChildren()) {

                data.add(videoSnapshot.getValue(funny_momments_row.class));
                //Create getter/setter method in funny_momments_row class if needed.
            }
        }

对于funny_momments_row,请使用java 命名约定。

【讨论】:

  • 感谢您的回答,但不起作用,数据仍然是空的,它应该 data.add(videoSnapshot.child("video 0").getValue(funny_momments_row.class));
猜你喜欢
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 2017-09-03
  • 1970-01-01
相关资源
最近更新 更多