由于Firebase参考错误,空指针异常错误导致View片段膨胀

时间:2018-10-27 14:33:54

标签: android firebase-realtime-database nullpointerexception

我在这个问题上陷入困境....

我的应用程序中不断出现此错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ValueEventListener com.google.firebase.database.DatabaseReference.addValueEventListener(com.google.firebase.database.ValueEventListener)' on a null object reference

现在,我要做的是发布Firebase数据库中列出的项目的结果。

这是我列出该列表的代码:

public class WatchListFragment extends Fragment {

    private static final String TAG = "WatchListFragment";
    private static final int NUM_GRID_COLUMNS = 3;
    private static final int GRID_ITEM_MARGIN = 5;

    //widgets
    private FrameLayout mFrameLayout;

    //reference for listening when items are added or removed from the watch list
    //vars
//    private DatabaseReference mReference = FirebaseDatabase.getInstance().getReference()
//            .child(getString(R.string.node_watch_list))
//            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());

    private PostAdapter mAdapter;
    private ArrayList<Post> mPosts;

    private RecyclerView mRecyclerView;

    private DatabaseReference mReference;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_watch_list, container, true);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.watchListRecyclerView);
        mFrameLayout = (FrameLayout) view.findViewById(R.id.watch_list_container);

        Log.d(TAG, "init: initializing.");
        mPosts = new ArrayList<>();

        //set the listener to the reference
        mReference.addValueEventListener(mLisenter);

        if(isAdded()){
            getResources().getString(R.string.app_name);
            mReference = FirebaseDatabase.getInstance().getReference()
                    .child(getString(R.string.node_watch_list))
                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        }

        mPosts = new ArrayList<Post>();
        mAdapter = new PostAdapter(this, mPosts);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.watchListRecyclerView); //unsere (Recycleriew)Liste aus dem Design wird in eine RecyclerView ungewandelt
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); //Hier könnten wir auch verschiedene Layouts festlegen. Bei der ListView, die vorher hatten, ist das Linearlayout fest eingestellt.
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL)); // Der Divider trennt die Zeilen mit einem Strich
        mRecyclerView.setAdapter(mAdapter); //Adapter wird gesetzt


//        RecyclerViewMargin itemDecorator = new RecyclerViewMargin(GRID_ITEM_MARGIN, NUM_GRID_COLUMNS);
//        mRecyclerView.addItemDecoration(itemDecorator);
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), NUM_GRID_COLUMNS);
//        mRecyclerView.setLayoutManager(gridLayoutManager);
//        mAdapter = new PostListAdapter(getActivity(), mPosts);
//        mRecyclerView.setAdapter(mAdapter);

        return view;
    }

    public void viewPost(String postId){
        ViewPostFragment fragment = new ViewPostFragment();
        Activity activity = getActivity();
        if (isAdded() && activity != null) {


        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();

        Bundle args = new Bundle();
        args.putString(getString(R.string.arg_post_id), postId);
        fragment.setArguments(args);

        transaction.replace(R.id.watch_list_container, fragment, getString(R.string.fragment_view_post));
        transaction.addToBackStack(getString(R.string.fragment_view_post));
        transaction.commit();

        mFrameLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mReference.removeEventListener(mLisenter);
    }

    ValueEventListener mLisenter = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(TAG, "onDataChange: a change was made to this users watch lits node.");

            DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

            Query query = reference.child("posts")
                    .orderByKey()
                    .equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());

            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    DataSnapshot dShot = dataSnapshot.getChildren().iterator().next();

                    for (DataSnapshot dShot2 : dShot.getChildren()) {
                        Post post = (Post) dShot2.getValue(Post.class);
                        mPosts.add(post);
                    }

                    mAdapter.notifyDataSetChanged();


                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };
}

logcat中标记的令人讨厌的代码行是这样的:         mReference.addValueEventListener(mLisenter);

我不能完全确定这就是问题所在。 我已经按照教程进行了搜索,并在谷歌上寻找答案,但是我仍然对为什么遇到这个特定问题感到困惑

1 个答案:

答案 0 :(得分:1)

您已注释掉mReference的初始化:

// private DatabaseReference mReference = FirebaseDatabase.getInstance().getReference() // .child(getString(R.string.node_watch_list)) // .child(FirebaseAuth.getInstance().getCurrentUser().getUid());

并将其初始化为null:

private DatabaseReference mReference;private DatabaseReference mReference = null;

稍后在您的onCreateView中,您尝试将侦听器添加到此空引用:

mReference.addValueEventListener(mLisenter);null.addValueEventListener(mLisenter)

编辑:现在,我看到您稍后在代码中初始化mReference,请尝试以下操作:

if(isAdded()){
  getResources().getString(R.string.app_name);
  mReference = FirebaseDatabase.getInstance().getReference()
    .child(getString(R.string.node_watch_list))  
    .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
  //move add listener here
  mReference.addValueEventListener(mLisenter);
}