需要帮助将firebase中的数据转换为string []数组。尝试了所有可用的方法,但坚持只获取最后一个值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了需要帮助将firebase中的数据转换为string []数组。尝试了所有可用的方法,但坚持只获取最后一个值相关的知识,希望对你有一定的参考价值。
我试图将存储在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;
}
}
答案
尝试在循环之外移动String[] main
,String[] 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);
以上是关于需要帮助将firebase中的数据转换为string []数组。尝试了所有可用的方法,但坚持只获取最后一个值的主要内容,如果未能解决你的问题,请参考以下文章