我想让我的应用程序读取总是变化的数据。我在youtube上尝试了该教程,打开应用程序时出现错误。
我要获取到android应用的示例数据:
对于代码,我尝试了
package com.example.dell.smarthouse;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class MenuTegangan extends AppCompatActivity {
private TextView mtegangan1;
private DatabaseReference myRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_tegangan);
mtegangan1 = (TextView) findViewById(R.id.tegangan1);
myRef.child("Tegangan 1").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
mtegangan1.setText(value);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
//Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
}
有关修复此代码的任何提示吗?
答案 0 :(得分:0)
这里的问题是myref
是否具有空指针?这是因为您忘记了对其进行初始化。试试这个
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("Tegangan 1");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
mtegangan1.setText(value);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
//Log.w(TAG, "Failed to read value.", error.toException());
}
});
希望这会有所帮助。干杯!
答案 1 :(得分:0)
实际上,您尚未发布错误日志,因此我们无法解决特定错误,但原因之一是您在未初始化的情况下访问myRef
,因此它将生成NullPointerException,因此请像波纹管一样在访问之前初始化对象
myRef = FirebaseDatabase.getInstance();