gpt4 book ai didi

Android Studio 适配器和 Firebase

转载 作者:行者123 更新时间:2023-11-30 05:12:46 26 4
gpt4 key购买 nike

当我在 Firebase 中删除某些内容时,为什么我的应用会崩溃?这是我的适配器

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

public Context mContext;
public List<Model> mPost;
private FirebaseStorage storage;
private FirebaseUser firebaseUser;
private StorageReference storageReference;
private ProgressDialog progressdialog;

public PostAdapter(Context mContext, List<Model> mPost) {
this.mContext = mContext;
this.mPost = mPost;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.row, parent, false);
return new PostAdapter.ViewHolder(view);
}

@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Model model = mPost.get(position);
holder.postname.setText(model.getPetname());
holder.postbreed.setText("Breed: " + model.getBreed());
holder.postage.setText("Age: " + model.getAge());
holder.postsize.setText("Size: " + model.getPetsize());
holder.postcolor.setText("Color: " + model.getPetcolor());
holder.postreason.setText(model.getReason());
holder.postdate.setText(model.getPostdate());
ownerinfo(holder.postby, holder.posterimage, model.getUserid());
Glide.with(mContext.getApplicationContext()).load(model.getPetpicture()).into(holder.postimage);

settinginfo(holder.settings,firebaseUser.getUid(),model.getUserid(),model.getPostid(),model.getBelong(),position);


isLike(model.getPostid(), holder.like);
numberLkes(holder.likes, model.getPostid());
getComments(model.getPostid(), holder.comments);



holder.postby.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, OtherUserProfile.class);
intent.putExtra("userid", model.getUserid());
mContext.startActivity(intent);
}
});

holder.posterimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, OtherUserProfile.class);
intent.putExtra("userid", model.getUserid());
mContext.startActivity(intent);
}
});


holder.like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")) {

FirebaseDatabase.getInstance().getReference().child("Likes").child(model.getPostid()).child(firebaseUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(model.getPostid()).child(firebaseUser.getUid()).removeValue();
}
}
});

holder.comment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsSection.class);
intent.putExtra("postid", model.getPostid());
intent.putExtra("userid", model.getUserid());
mContext.startActivity(intent);
}
});

holder.comments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, CommentsSection.class);
intent.putExtra("postid", model.getPostid());
intent.putExtra("userid", model.getUserid());
mContext.startActivity(intent);
}
});


}

@Override
public int getItemCount() {
return mPost.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

public CircleImageView posterimage;
public ImageView postimage, like, comment, settings;
public Button adoptnme;
public TextView postby, postname, postbreed, postage, postsize, postcolor, postreason, likes, postdate, comments;

public ViewHolder(View itemView) {
super(itemView);


comments = itemView.findViewById(R.id.comments);
comment = itemView.findViewById(R.id.comment);
posterimage = itemView.findViewById(R.id.posterimage);
postby = itemView.findViewById(R.id.postby);
postdate = itemView.findViewById(R.id.postdate);
postimage = itemView.findViewById(R.id.postimage);
like = itemView.findViewById(R.id.like);
likes = itemView.findViewById(R.id.likes);
postname = itemView.findViewById(R.id.postname);
postbreed = itemView.findViewById(R.id.postbreed);
postage = itemView.findViewById(R.id.postage);
postsize = itemView.findViewById(R.id.postsize);
postcolor = itemView.findViewById(R.id.postcolor);
postreason = itemView.findViewById(R.id.postreason);
settings = itemView.findViewById(R.id.postsetting);


}

}

private void getComments(String postid, final TextView comments) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments").child(postid);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
comments.setText("View all " + dataSnapshot.getChildrenCount() + " comments");
}

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

}
});
}

private void isLike(String postid, final ImageView imageView) {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Likes").child(postid);

reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(firebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.like);
imageView.setTag("liked");

} else {
imageView.setImageResource(R.drawable.ic_favorite_border_black_24dp);
imageView.setTag("like");
}
}

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

}
});
}

private void numberLkes(final TextView likes, String postid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() == 1 || dataSnapshot.getChildrenCount() == 0) {
likes.setText(dataSnapshot.getChildrenCount() + " Like");
} else {
likes.setText(dataSnapshot.getChildrenCount() + " Likes");
}
}

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

}
});
}

private void ownerinfo(final TextView postby,
final CircleImageView posterimage,
String userid) {
DatabaseReference reference = FirebaseDatabase.getInstance()
.getReference("User").child(userid);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
UserAdapter userAdapter = dataSnapshot.getValue(UserAdapter.class);
Glide.with(mContext.getApplicationContext()).load(userAdapter.getProfilepic()).into(posterimage);
// Glide.with(mContext.getApplicationContext()) .using(new FirebaseImageLoader()) .load(storageReference) .signature(new StringSignature(uri.toString())) .diskCacheStrategy(DiskCacheStrategy.ALL) .placeholder(placeHolder) .into(imageView);
postby.setText(userAdapter.getName());
}


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

}
});


}

private void settinginfo(final ImageView setting, final String userid, final String poserid, final String postid, final String pettype, final int position) {

setting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (poserid.equals(userid)) {
PopupMenu popupMenu = new PopupMenu(mContext, setting);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {

switch (item.getItemId()) {
case R.id.editPost:
// item two clicked
return true;
case R.id.deletePost:
AlertDialog alertDialog = new AlertDialog.Builder(mContext)
//set icon

//set title
.setTitle("Confirmation of deletion")
//set message
.setMessage("Delete this post?")
//set positive button
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
progressdialog = new ProgressDialog(mContext);
progressdialog.setMessage("Deleting...");
progressdialog.show();
FirebaseDatabase.getInstance().getReference().child("Likes").child(postid).removeValue();
FirebaseDatabase.getInstance().getReference().child("Comments").child(postid).removeValue();
String storageUrl = pettype+"/"+postid;
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child(storageUrl);
FirebaseDatabase.getInstance().getReference(pettype).child(postid).removeValue();
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
progressdialog.dismiss();
Toast.makeText(mContext, "Post has has been deleted",Toast.LENGTH_LONG).show();




}
});





}
})
//set negative button
.setNegativeButton("Dont delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what should happen when negative button is clicked

}
})
.show();
return true;
}

return false;
}
});
popupMenu.inflate(R.menu.setting_photo);
popupMenu.show();

}
else
{
PopupMenu popupMenu = new PopupMenu(mContext, setting);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {

switch (item.getItemId()) {
case R.id.reportPost:
// item two clicked
return true;
}

return false;
}
});
popupMenu.inflate(R.menu.report_photo);
popupMenu.show();
}
}
});

}
}

使用该适配器后它崩溃并出现错误

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.jasper.happy_paws.Model.getUserid()' on a null object reference
at com.example.jasper.happy_paws.PostAdapter.onBindViewHolder(PostAdapter.java:71)
at com.example.jasper.happy_paws.PostAdapter.onBindViewHolder(PostAdapter.java:40)

最佳答案

如果您想防止您的应用程序崩溃,这是一个快速的解决方案。这不是最好的解决方案,但这确实会阻止应用程序崩溃。

尝试/捕捉

在将数据设置到 View 中时,请确保在代码中使用 try/catch 语句来捕获空指针

正如您所说,根据您的日志,当您尝试使用方法 mode.getuserUid()(类似的方法)从模型中获取 uid 时,会出现一个空指针。

所以现在你将这部分绑定(bind)在 try/catch 中并捕获空指针(如果有的话)

try{
//your code comes here like in your case you are grabbing so much data from model object
}catch(NullPointerException e){
//here you can show the default data you want if there is no value deefined
}

关于Android Studio 适配器和 Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53454315/

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