java.lang.NullPointerException:无法为child()中的参数'pathString'传递null-MessagesDbRef中发生错误

时间:2018-11-01 20:15:16

标签: java android firebase nullpointerexception runtime-error

执行我的应用程序时,出现以下错误:

  

java.lang.NullPointerException:无法为child()中的参数'pathString'传递null

但是我之前没有收到此错误。有人可以帮助我吗?

请查看错误控制台,并在Java代码上方

控制台错误:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: br.com.devbrains.nerdspace, PID: 12393
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.devbrains.nerdspace/br.com.devbrains.nerdspace.activity.MainActivity}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2812)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2890)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1611)
                      at android.os.Handler.dispatchMessage(Handler.java:106)
                      at android.os.Looper.loop(Looper.java:171)
                      at android.app.ActivityThread.main(ActivityThread.java:6633)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
                   Caused by: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
                      at com.google.firebase.database.DatabaseReference.child(com.google.firebase:firebase-database@@16.0.3:101)
                      at br.com.devbrains.nerdspace.fragment.MessagesFragment.onCreateView(MessagesFragment.java:85)
                      at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
                      at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
                      at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
                      at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
                      at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
                      at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
                      at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
                      at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
                      at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
                      at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
                      at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
                      at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
                      at br.com.devbrains.nerdspace.activity.MainActivity.onStart(MainActivity.java:411)
                      at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1335)
                      at android.app.Activity.performStart(Activity.java:7104)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2775)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2890) 
                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1611) 
                      at android.os.Handler.dispatchMessage(Handler.java:106) 
                      at android.os.Looper.loop(Looper.java:171) 
                      at android.app.ActivityThread.main(ActivityThread.java:6633)

MessagesFragment.java

MessagesFragment中的第一个错误,该错误发生在MessagesDbRef中,但是firebase不为空。

public class MessagesFragment extends Fragment {
    private static final String TAG = MessagesFragment.class.getSimpleName();

    private FirebaseAuth mAuth;
    private FirebaseUser user;
    private DatabaseReference userDbRef;
    private DatabaseReference messagesDbRef;
    private DatabaseReference conversationsDbRef;
    private FirebaseRecyclerAdapter firebaseRecyclerAdapter;

    private RecyclerView recyclerViewConversations;
    private Context context;

    ImageView imgViewNoMessages;
    TextView txtNoMessages;

    private String currentUserId;

    public MessagesFragment() {
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View messagesView = inflater.inflate(R.layout.fragment_messages, container, false);

        imgViewNoMessages = (ImageView) messagesView.findViewById(R.id.image_no_messages);
        txtNoMessages = (TextView) messagesView.findViewById(R.id.text_no_messages);

        this.context = getContext();

        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();

        if (user != null) {
            currentUserId = user.getUid();
        }

        recyclerViewConversations = (RecyclerView) messagesView.findViewById(R.id.rv_conversations);

        userDbRef = FirebaseDatabase.getInstance().getReference().child("Users");
        userDbRef.keepSynced(true);

        conversationsDbRef = FirebaseDatabase.getInstance().getReference().child("Chat").child(currentUserId);
        conversationsDbRef.keepSynced( true );

        messagesDbRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserId);
        messagesDbRef.keepSynced(true);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);

        recyclerViewConversations.setHasFixedSize(true);
        recyclerViewConversations.setLayoutManager(linearLayoutManager);

        return messagesView;
    }

MainActivity.java

这里的错误显示在onStart()方法中。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();

        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();

        nerdspaceProgressBar = NerdspaceProgressBar.getInstance();

        //TODO: Ação do botão FAB
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), CreateNewsActivity.class));
            }
        });

        if (user != null) {
            String userUid = user.getUid();
            currentUserDbRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userUid);
            currentUserDbRef.addValueEventListener(new ValueEventListener() {
                @SuppressLint("NewApi")
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                        image = (String) dataSnapshot.child("image").getValue();
                        if (image == null || image.equals("default")) {
                            if (getApplicationContext() != null) {
                                GlideApp.with(getApplicationContext())
                                        .load(image)
                                        .placeholder(R.drawable.stormtropper)
                                        .error(R.drawable.stormtropper)
                                        .fitCenter()
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .listener(new RequestListener<Drawable>() {
                                            @Override
                                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                                Log.e(TAG, "Error loading image", e);
                                                return false;
                                            }

                                            @Override
                                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                                return false;
                                            }
                                        })
                                        .into(civNavHeader);
                            }
                        }
                        String name = (String) dataSnapshot.child("name").getValue();
                        String email = user.getEmail();

                        if (getApplicationContext() != null) {
                            GlideApp.with(getApplicationContext())
                                    .load(image)
                                    .placeholder(R.drawable.stormtropper)
                                    .error(R.drawable.stormtropper)
                                    .fitCenter()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .listener(new RequestListener<Drawable>() {
                                        @Override
                                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                            Log.e(TAG, "Error loading image", e);
                                            return false;
                                        }

                                        @Override
                                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                            return false;
                                        }
                                    })
                                    .into(civNavHeader);
                        }
                        tvNavHeaderUserName.setText(capitalizeFully(name));
                        tvNavHeaderUserEmail.setText(email);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                }
            });
        }
        navigationView.setNavigationItemSelectedListener(this);
}

    @Override
    protected void onStart() {
        super.onStart();
        if (user == null) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            currentUserDbRef.child("online").setValue("true");
            civNavHeader.setBorderColor(getResources().getColor(R.color.colorOnline));
        }
    }

1 个答案:

答案 0 :(得分:0)

似乎您没有共享类的所有代码。

所以我只有猜测;

if (user != null) {
   currentUserId = user.getUid();
 }

这些行说如果用户为空,则currentUserId将为空。

    conversationsDbRef = FirebaseDatabase.getInstance().getReference().child("Chat")
.child(currentUserId);

在这行代码中,似乎传递的参数 currentUserId 为null,并且该null是NullPointerException的原因