gpt4 book ai didi

java - Firebase 用户界面 : RecyclerView items are not shown

转载 作者:行者123 更新时间:2023-12-02 08:47:06 25 4
gpt4 key购买 nike

我一直在尝试使用 RecyclerView 在我的应用中实现 Firebase-UI。我使用实时数据库和 Firebase-UI 在聊天应用程序中创建了一个 recyclerView 用户列表,我想从 ProfileActivity 检索数据并将其显示在我的 AllUsersActivity 中。问题是 RecyclerView 项目未显示,并且我收到此错误:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.schoolteacher, PID: 19631
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ChildEventListener com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)' on a null object reference
at com.firebase.ui.database.FirebaseArray.onCreate(FirebaseArray.java:54)
at com.firebase.ui.common.BaseObservableSnapshotArray.addChangeEventListener(BaseObservableSnapshotArray.java:97)
at com.firebase.ui.database.FirebaseRecyclerAdapter.startListening(FirebaseRecyclerAdapter.java:52)
at com.example.schoolteacher.AllUsersActivity.onStart(AllUsersActivity.java:112)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1419)
at android.app.Activity.performStart(Activity.java:7479)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3454)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

这是我的代码:

AllUsersActivity.java

public class AllUsersActivity extends AppCompatActivity {

private DatabaseReference mUsersDatabase;
private LinearLayoutManager linearLayoutManager;
private RecyclerView recyclerView;
private Query query;


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

recyclerView = findViewById(R.id.recycler_view);

linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);

query = FirebaseDatabase.getInstance().getReference().child("Users");


}



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

FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {

@Override
protected void onBindViewHolder(@NonNull UsersViewHolder holder, int position, @NonNull Users model) {

holder.setName(model.getName());
}

@Override
public UsersViewHolder 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.activity_all_users, parent, false);

return new UsersViewHolder(view);
}
};

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

@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}


}


class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;

UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}

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

个人资料信息 Activity

public class ProfileInfoActivity extends AppCompatActivity {

private DatabaseReference mDatabaseReference;
private FirebaseUser mCurrentUser;

private CircleImageView mDisplayImage;
private TextView mName;
private TextInputEditText mEditName, mEmail;

private TextView mStatus;
private ImageButton mStatusBtn;

private static final int GALLERY_PICK = 1;

private StorageReference mImageStorage;

private ProgressDialog mProgressDialog;

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


mDisplayImage = findViewById(R.id.circle_image);
mName = findViewById(R.id.name);
mEditName = findViewById(R.id.et_name);
mEmail = findViewById(R.id.et_email_address);
mStatus = findViewById(R.id.status);
mStatusBtn = findViewById(R.id.status_btn);

mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String userID = mCurrentUser.getUid();

mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

String name = dataSnapshot.child("name").getValue().toString();
String et_name = dataSnapshot.child("name").getValue().toString();
String et_email_adress = dataSnapshot.child("email").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

mName.setText(name);
mEditName.setText(et_name);
mEmail.setText(et_email_adress);
mStatus.setText("Teacher at "+ status);


Picasso.get().load(image).into(mDisplayImage);

}

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

}
});

mDisplayImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});


mStatusBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//send status data to changeSchoolActivity to retrieve it
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(ProfileInfoActivity.this, ChangeSchoolActivity.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});


}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == GALLERY_PICK && resultCode == RESULT_OK ) {
Uri imageUri = data.getData();

CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.start(this);

//Toast.makeText(ProfileInfoActivity.this, imageUri, Toast.LENGTH_SHORT).show();
}

if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {

mProgressDialog = new ProgressDialog(ProfileInfoActivity.this);
mProgressDialog.setTitle("Uploading Image...");
mProgressDialog.setMessage("Please wait while we upload and process the image");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();


Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();


final StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");

filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String download_url = uri.toString();
mDatabaseReference.child("image").setValue(download_url).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mProgressDialog.dismiss();
Toast.makeText(ProfileInfoActivity.this,"Success Uploading",Toast.LENGTH_SHORT).show();
}
});

}
});
}
});


} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}

最佳答案

根据您的最新评论:

protected void onStart() { super.onStart(); firebaseRecyclerAdapter.startListening(); }

是发生错误的行。要解决此问题,请通过添加以下代码行将 firebaseRecyclerAdapter 变量创建为全局变量:

private FirebaseRecyclerAdapter firebaseRecyclerAdapter;

紧接着:

private Query query;

并从代码中删除类型声明:

//FirebaseRecyclerAdapter does not exist anymore
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(firebaseRecyclerOptions) {
@NonNull
@Override
public UsersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new UsersViewHolder(mView);
}

@Override
protected void onBindViewHolder(@NonNull UsersViewHolder holder, int position, @NonNull Users model) {
holder.setName(model.getName());

}
};

关于java - Firebase 用户界面 : RecyclerView items are not shown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61012146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com