gpt4 book ai didi

java - 如何从 Firebase 中检索 ListView 中的数据

转载 作者:搜寻专家 更新时间:2023-11-01 09:31:22 25 4
gpt4 key购买 nike

Data Structure in Firebase

你能帮我解决这个问题吗,我尝试在 Listview 中显示来自 firebase 的数据,但没有显示任何内容!

ListView listView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
ArrayList<String> arrayList = new ArrayList<>();

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

firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference= firebaseDatabase.getReference("Users");


listView=(ListView) findViewById(R.id.list);
final ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this ,android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value=dataSnapshot.getValue(String.class);
arrayList.add(value);
arrayAdapter.notifyDataSetChanged();

}

最佳答案

public class MainActivity extends AppCompatActivity{
ListView listView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;

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

firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");


listView = (ListView) findViewById(R.id.lists);

Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value=dataSnapshot.getValue(String.class);
arrayList.add(value);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);

}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

}}

这个监听器实际上是用于列表的,所以它不是来自监听器。此外,由于用户未通过身份验证,您需要将数据库中的规则更改为:-

 {
"rules": {
".read": "true",
".write": "true"
}
}

关于java - 如何从 Firebase 中检索 ListView 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46999035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com