简体   繁体   中英

NullPointerException while getting data via another class from firebase Database

I created a class called UserInfo to get all user data from firebase database. Here is the method I used to get firebase data (username).

 public String getUsername() {
        final Firebase usernameLink = new Firebase(firebaseLink + getUid());
        usernameLink.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                username = (String) dataSnapshot.getValue();
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
            }
        });
        return username;
    }

And the firebase link has no problem. And it gives the username too.

But in another class I want to get the username.

So I made a object of that class..

UserInfo userInfo = new UserInfo();

And to get the username,

username = userInfo.getUsername();

I wrote the previous code in my onCreate method.

On a button click in my app, I am trying to add the username as my child.

send_request_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request_text = request_msg.getText().toString();
                URL = new Firebase(firebaseUrl);
               Firebase addChild = URL.child(username);
                                addChild.setValue("hhhhh");        
                        }
                );

Well this code works when I replace username with some dummy predefined string data. But when I add username it gives me the following error.

java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
 at com.firebase.client.Firebase.child(Firebase.java:187)
 at com.buckydroid.anonchat.SendRequest$1$1.onClick(SendRequest.java:67)
 at android.view.View.performClick(View.java:5637)
 at android.view.View$PerformClick.run(View.java:22433)
 at android.os.Handler.handleCallback(Handler.java:751)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:6126)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Make sure your variable firebaseLink is initialized and is assigned to some data before running this method. The NullPointerException output I'm seeing tells me that you are trying to pass a null variable to the pathString variable of the Firebase class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM