我有一个firebase数据库,我正在存储一个数字作为项目的索引。我使用我的数据库类
访问它public class IndexCount {
private String Streaming;
public IndexCount(String Streaming){
this.Streaming = Streaming;
}
public void databaseIndexCounter( ){
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference dbref = db.getReference().child("Apps").child("IndexCount");
dbref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Integer Stream = dataSnapshot.child("Streaming").getValue(Integer.class);
Streaming = Stream.toString();
Log.i("streamcount: ",Streaming);
}
}
}
我想访问此类之外的Streaming字符串,并在我的主活动中使用它来填充textview。我怎么能做到这一点? 我以为从我的主要活动中调用这个就可以了。
String streamcounter = new String();
IndexCount indexcount = new IndexCount(streamcounter);
tvstreaming = (TextView)view.findViewById(R.id.streamcount);
indexcount.databaseIndexCounter();
Log.i("stream count: ",streamcounter);
tvstreaming.setText(streamcounter);
但日志不会触发,所以我假设我的代码是错误的lol。谢谢你们
答案 0 :(得分:1)
onDataChange将在另一个线程(不是主线程)中执行,所以你需要等到它完成它的工作,然后做你想要的。
public class IndexCount {
private String Streaming;
public IndexCount(String Streaming){
this.Streaming = Streaming;
}
public void databaseIndexCounter( ){
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference dbref = db.getReference().child("Apps").child("IndexCount");
dbref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Integer Stream = dataSnapshot.child("Streaming").getValue(Integer.class);
Streaming = Stream.toString();
Log.i("streamcount: ",Streaming);
// call it here
nextStep();
}
}
}
public void nextStep(){
Log.i("stream count: ",streamcounter);
tvstreaming.setText(streamcounter);
}
并从您的主要活动
String streamcounter = new String();
IndexCount indexcount = new IndexCount(streamcounter);
tvstreaming = (TextView)view.findViewById(R.id.streamcount);
indexcount.databaseIndexCounter();