我尝试通过Android应用更新Firebase Realtime数据库中的数据。只有在我打开应用程序并等待一段时间后,它才会偶尔工作。在大多数情况下,它不起作用。就我而言,工作意味着数据将在云中更新。我想知道为什么它有时会起作用而有时却不起作用。 Logcat中没有错误或警告。一旦运行,它将继续运行,直到重新启动该应用程序为止。
DbHelper类
public class DbHelper {
static final String TAG = "ttt";
int count = 0;
private static FirebaseDatabase database = FirebaseDatabase.getInstance();
private static DatabaseReference myRef = database.getReference("message");
TextView tv;
public DbHelper(final TextView tv){
this.tv = tv;
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
tv.setText(text);
Log.d(TAG, "Value is: " + text);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
public void testing(){
myRef.setValue("test"+count++);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
TextView textTesting;
DbHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textTesting = (TextView)findViewById(R.id.text_testing);
dbHelper = new DbHelper(textTesting);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dbHelper.testing();
}
});
}
}
已添加
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
Log.d(TAG, "connected");
} else {
Log.d(TAG, "not connected");
}
}
@Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
Logcat
11-14 20:26:58.956 19329-19384 /? V / FA:连接尝试已在进行中
11-14 20:26:58.956 19329-19384 /? V / FA:连接尝试已在进行中
11-14 20:26:58.961 19329-19384 /? V / FA:活动已恢复,时间:167270724
11-14 20:26:58.986 19329-19384 /? D / FA:已连接到远程服务
11-14 20:26:59.001 19329-19329 /? I /时间轴:时间轴:Activity_idle ID:android.os.BinderProxy@34fb88b7时间:15941479
11-14 20:26:59.006 19329-19384 /? V / FA:处理排队的服务任务:4
11-14 20:26:59.056 19329-19336 /? I / art:忽略第二个调试器-接受和删除
11-14 20:26:59.541 19329-19329 /? D / ViewRootImpl:ViewPostImeInputStage ACTION_DOWN
11-14 20:26:59.631 19329-19329 /? D / ttt:值是:test0
11-14 20:27:02.366 19329-19329 /? D / ViewRootImpl:ViewPostImeInputStage ACTION_DOWN
11-14 20:27:02.451 19329-19329 /? D / ttt:值是:test1
11-14 20:27:04.166 19329-19384 /? V / FA:不活动,正在与服务断开连接
11-14 20:28:07.721 19329-19329 /? D / FA:服务连接已暂停