我正在使用Firebase创建一个应用,用户可以在其中分享报价。数据插入成功,在插入每个值后,它在数据库中看起来像这样。 请查看此图像以获取数据库值:
我想获取ArrayList中的所有数据。并且public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
this.localView = paramLayoutInflater.inflate(R.layout.fragmenthome, paramViewGroup, false);
story = (TextView) localView.findViewById(R.id.story_text);
rl = (RelativeLayout) localView.findViewById(R.id.rlLayout);
linearLayout = (LinearLayout) localView.findViewById(R.id.bottom_bar);
imgRefresh = (ImageView) localView.findViewById(R.id.refreshStory);
databaseReference = FirebaseDatabase.getInstance().getReference().child("stories");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
storiesary = new ArrayList<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
storiesary.add(childSnapshot.getValue().toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
imgRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setStory();
}
});
return localView;
}
public void setStory()
{
int arraysize = storiesary.size();
final int arrayposition1 = (new Random()).nextInt(arraysize);
story.setText(storiesary.get(arrayposition1));
}
的刷新按钮应该将TextView更新为将从ArrayList中随机选择的新值。我尝试过这样的事情。但它不起作用。它显示nullpointerexception。
{{1}}
答案 0 :(得分:2)
试试这个
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
storiesary = new ArrayList<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
HashMap map =(HashMap) childSnapshot.getValue();
if(map!=null) {
storiesary.add(map.get("storytext"));
}
//or
String name = (String) childSnapshot.child("storytext").getValue();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG,"Error");
}
});