Firebase Noob java.lang.NullPointerException:无法为child()中的参数“ pathString”传递null

时间:2018-08-05 19:55:03

标签: android firebase mobile firebase-realtime-database

我正在尝试添加一项功能,使用户可以点击所有用户的列表并查看该用户的个人资料。添加此代码后,我收到此错误。 Image of database当我点击用户列表以启动意图时,并且当我查看用户设置之前正在工作,现在却无法检索数据时,就会发生错误。

08-05 15:42:33.372 4697-4697/com.example.android.lapitchat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.lapitchat, PID: 4697
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.lapitchat/com.example.android.lapitchat.ProfileActivity}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
 Caused by: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
    at com.google.firebase.database.DatabaseReference.child(Unknown Source)
    at com.example.android.lapitchat.ProfileActivity.onCreate(ProfileActivity.java:38)
    at android.app.Activity.performCreate(Activity.java:6757)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)

这是我的代码的状态

public class ProfileActivity extends AppCompatActivity {

private ImageView mProfileImage;
private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Button mProfileSendReqBtn;

private DatabaseReference mUsersDatabase;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    String user_id = getIntent().getStringExtra("user id");

    mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);

    mProfileImage =  findViewById(R.id.profileImage);
    mProfileName = findViewById(R.id.profileName);
    mProfileStatus = findViewById(R.id.profileStatus);
    mProfileFriendsCount = findViewById(R.id.profileFriendsCount);
    mProfileSendReqBtn = findViewById(R.id.profileSendReqBtn);

    mUsersDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            String display_name = Objects.requireNonNull(dataSnapshot.child("name").getValue()).toString();
            String status = Objects.requireNonNull(dataSnapshot.child("status").getValue()).toString();
            String image = Objects.requireNonNull(dataSnapshot.child("image").getValue()).toString();

            mProfileName.setText(display_name);
            mProfileStatus.setText(status);


        }

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

        }
    });

}

}

import static com.example.android.lapitchat.R.layout.*;




protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(activity_users);
    mToolbar = findViewById(R.id.users_appbar);
    mUsersList = findViewById(R.id.users_list);
    mUsersList.hasFixedSize();
    mUsersList.setLayoutManager(new LinearLayoutManager(this));
    mUserDatabase = FirebaseDatabase.getInstance().getReference().child("User");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setTitle("All Users");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
protected void onStart() {
    super.onStart();
    startListening();
}

public void startListening() {
    Query query = FirebaseDatabase.getInstance()
            .getReference()
            .child("Users")
            .limitToLast(50);



    FirebaseRecyclerOptions<Users> options =
            new FirebaseRecyclerOptions.Builder<Users>()
                    .setQuery(query, Users.class)
                    .build();

    FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Users, UserViewHolder>(options) {
        @Override
        public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // Create a new instance of the ViewHolder, in this case we are using a custom
            // layout called R.layout.message for each item
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
            return new UserViewHolder(view);
        }

        @Override
        protected void onBindViewHolder(UserViewHolder holder, int position, Users model) {// Bind the Chat object to the ChatHolder
            holder.setName(model.name);
            holder.setStatus(model.status);

            final String user_id = getRef(position).getKey();

            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent profileIntent = new Intent(UsersActivity.this, ProfileActivity.class);
                    profileIntent.putExtra("user_id", user_id);
                    startActivity(profileIntent);

                }
            });



        }
    };
    mUsersList.setAdapter(adapter);
    adapter.startListening();
}

public static class UserViewHolder extends RecyclerView.ViewHolder {
    View mView;

    public UserViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setName(String name) {
        TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
        userNameView.setText(name);
    }

    public void setStatus(String status){
        TextView statusTextView = (TextView) mView.findViewById(R.id.user_single_status);
        statusTextView.setText(status);
    }

}

}

2 个答案:

答案 0 :(得分:1)

这是代码中唯一可以将空值传递给child()的地方:

String user_id = getIntent().getStringExtra("user id");

mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);

因此,user_id可能为空。像这样使用它之前,您应该先检查它。

答案 1 :(得分:1)

我假设这是来自LapitChatApp教程。如果是这样,则需要在ProfileActivity.java中验证是通过user_id方法传递from_user_id还是通过getIntent()方法传递onCreate。您可以在 final String user_id; String data = getIntent().getStringExtra("user_id"); if (data == null) { user_id = getIntent().getStringExtra("from_user_id"); } else { user_id = getIntent().getStringExtra("user_id"); } 方法中使用if来简单地做到这一点。

library(tidyverse)

df %>% rownames_to_column() %>%
    gather(measure, value, -rowname) %>%
    group_by(rowname) %>%
    na.omit() %>%
    mutate(measure = paste0("col", row_number())) %>%
    spread(measure, value) %>%
    ungroup() %>%
    select(-rowname)
#    col1  col2  col3
# 1     3     1    NA
# 2     6     7     3
# 3     9     8    NA