我有一个Activity
,我必须使用另一个类DataBase中的函数。在DataBase中,代码必须从我的 FireBase数据库获取信息,然后返回ArrayList作为结果。但是当我在takeDataFromFirebase
中使用函数null
时,它的大小为null
。如何将带有FireBase信息的数组添加到我的活动中?
public class DataBase{
public ArrayList<String> arraylist = new ArrayList<>();
public ArrayList<String> takeDataFromFirebase(DatabaseReference dRef) {
usersRef = dRef.child(USERS_CHILD);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
DatabaseReference messagesRef = usersRef.child(userKey).child(USER_MESSAGES);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
messageText = dSnapshot.child(USER_MESSAGE_TEXT).getValue(String.class);
arrayList.add(messageText);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
return null;
}
}
以及我使用此方法的活动:
public class Categories extends AppCompatActivity{
private static final String TAG = "CATEGORIES";
FirebaseAuth mAuth;
private ListView all_problems_list_view;
private Button add_problem_button, signOut;
private static long back_pressed;
FirebaseDatabase mDataBase;
DatabaseReference dRef;
DatabaseReference userRef;
DataBase dataBaseFunctions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_categories);
dataBaseFunctions = new DataBase();
mAuth = FirebaseAuth.getInstance();
mDataBase = FirebaseDatabase.getInstance();
dRef = mDataBase.getReference();
userRef = dRef.child("Users");
//region add all items
all_problems_list_view = (ListView) findViewById(id.all_problems_list_view);
add_problem_button = (Button) findViewById(id.add_problem_button);
signOut = (Button) findViewById(id.SignOutBut);
//endregion
//region set onClick to buttons
signOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logout();
}
});
add_problem_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Categories.this, sendEmailActivity.class));
}
});
//endregiond
ArrayList<String> list = dataBaseFunctions.takeDataFromFirebase(dRef);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, list);
all_problems_list_view.setAdapter(adapter);
}
答案 0 :(得分:1)
你的函数takeDataFromFirebase返回null,所以你的结果总是为null。用你想得到的数组替换这个null,我想是arrayList。