Firebase数据库引用错误

时间:2018-01-13 16:01:46

标签: android firebase firebase-realtime-database

在运行下面的代码时,我收到此错误:

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)'

我在第dataRef.child(dbs).addValueEventListener(new ValueEventListener()行收到错误。我不确定是什么问题。

public class UTFragment extends Fragment {
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
SharedPreferences prefs = getActivity().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
        String savedCollname= prefs.getString("collname", null);
        dataRef = FirebaseDatabase.getInstance().getReference().child(savedCollname);
}

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
UTFragment utFragment = new UTFragment();
            UTFragment.MyAsync myTask = utFragment.new MyAsync(dbs,data);
            myTask.execute();
}

class MyAsync extends AsyncTask<Void, Void, Void> {
String dbs;
 public MyAsync(String dbs){
this.dbs = dbs;
}
@Override
            protected void onProgressUpdate(Void... values) {
dataRef.child(dbs).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        //do something
}}

2 个答案:

答案 0 :(得分:1)

错误非常清楚地说明了问题所在。当您在其上调用dataRef方法时,您的字段child()尚未初始化,其他字词的值为null

要解决此问题,必须在任务更新其进度之前调用onCreateView()方法。

答案 1 :(得分:1)

问题在于您第二次实例化片段。您不需要第二个片段才能使用AsyncTask。您只需调用AsyncTask:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            MyAsync myTask = new MyAsync(dbs,data);
            myTask.execute();
}