需要帮助将数据从Firebase获取到string []数组中。尝试了所有可用方法,但只获取了最后一个值

时间:2019-04-20 05:09:52

标签: java android firebase

我正在尝试将存储在Firebase中的所有值放入两个单独的string []数组中。我正在获取值,但在将其显示到列表视图时,它仅显示最后添加的值。我也在使用自定义适配器类。

Database.child("users").child(mUserId).child("locs").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot ds : dataSnapshot.getChildren()) {

            final String[] main = {(String) ds.child("title").getValue()};
            final String[] sub = {(String) ds.child("addr").getValue()};
            System.out.println(main);//here i am getting 5 outputs like  [Ljava.lang.String;@88b5c49. i have 5 values in firebase too

            CustomAdapter adapter2 = new CustomAdapter(Location.this, main, sub);
            list.setAdapter(adapter2);
        }
    }
});

自定义适配器类

public class CustomAdapter extends ArrayAdapter<String>{

    private final Activity context;
    private final String[] main;
    private final String[] sub;
    public CustomAdapter(Activity context,
                         String[] main, String[] sub) {
        super(context, R.layout.layout, main);
        this.context = context;
        this.main = main;
        this.sub = sub;

    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView= inflater.inflate(R.layout.layout, null, true);
        TextView txtTitle = (TextView) rowView.findViewById(R.id.title);
        TextView txtSub=rowView.findViewById(R.id.subtitle);
        txtTitle.setText(main[position]);
        txtSub.setText(sub[position]);
        return rowView;
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将String[] mainString[] sub移动到循环之外。然后尝试将所有值添加到循环内的这些数组中。然后在完成循环后调用这些

CustomAdapter adapter2 = new CustomAdapter(Location.this, main, sub);
list.setAdapter(adapter2);

整个代码应该是这样的。

final String[] main; // declare it with the size it needs.
final String[] sub;  // declare it with the size it needs.              
for(DataSnapshot ds:dataSnapshot.getChildren()) {
   // sum your result to main and sub
}
CustomAdapter adapter2 = new CustomAdapter(Location.this, main, sub);
list.setAdapter(adapter2);