我从addOnCompleteListener内的FirebaseFireStore数据库中成功获取了数据,并且可以使用Toast显示数据,但无法使用arrayList.add(object)方法将数据添加到ArrayList中。代码完成后,它将数组大小显示为0。:(
代码如下:
private void getDataFromFireBase()
{
try
{
final SimpleDateFormat dateFormat= new SimpleDateFormat("MMM d, h:mm a");
objFirebaseFirestore.collection(COL_THOUGHTS).get().
addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isComplete())
{
for(QueryDocumentSnapshot data:task.getResult())
{
Timestamp timestampValue=data.getTimestamp("timestamp");
Toast.makeText(MainActivity.this, "Fetching data", Toast.LENGTH_SHORT).show();
/*Toast.makeText(MainActivity.this, data.getString("username")
+"\n"+data.getString("category")
+"\n"+data.getString("thoughtText")
+"\n"+data.getId()
+"\n"+data.getLong("numOfLikes")
+"\n"+ dateFormat.format(timestampValue.toDate()), Toast.LENGTH_SHORT).show();*/
//Toast.makeText(MainActivity.this, data.getString("username"), Toast.LENGTH_SHORT).show();
String userNameDummy=data.getString("username");
String categoryDummy=data.getString("category");
String thoughtTextDummy=data.getString("thoughtText");
String idDummy=data.getId();
String dateDummy=dateFormat.format(timestampValue.toDate());
long numOfLikesDummy=data.getLong("numOfLikes");
/*thoughtsModelClassArrayList.add(new ThoughtsModelClass(
userNameDummy,
categoryDummy,
thoughtTextDummy,
idDummy,
dateDummy,
0,
numOfLikesDummy
));*/
ThoughtsModelClass obj=new ThoughtsModelClass(userNameDummy,categoryDummy,
thoughtTextDummy,idDummy,dateDummy,0,numOfLikesDummy) ;
thoughtsModelClassArrayList.add(obj);
//Toast.makeText(MainActivity.this, thoughtsModelClassArrayList.size(), Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
catch (Exception e)
{
Toast.makeText(this, "getDataFromFireBase:"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}