我向删除功能添加了新代码,以便在用户删除文件时为其提供分数。只会有四个用户(我的家庭成员),因此不是使用我刚才使用过的if语句创建带有检查和分配的自动ID系统。在添加换点代码之前,它工作正常。现在,当您按下Delete键时,它就会崩溃。
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
holder.lengthText.setText(choreList.get(position).getTime());
holder.descriptionText.setText(choreList.get(position).getChore());
final String chore_id = choreList.get(position).choreId;
dFirestore = FirebaseFirestore.getInstance();
holder.removeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
// CharSequence rmText = "Chore Finished! Good job!";
//int duration = Toast.LENGTH_LONG;
DocumentReference doc = dFirestore.collection("choreList").document(chore_id);
doc.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
//userid = "com.example.choretest.userID";
userid = context.getSharedPreferences("com.example.choretest", context.MODE_PRIVATE).getString("userID", "");
if(userid == "0"){
DocumentReference ref = dFirestore.collection("userList").document("anya");
ref.update("points", FieldValue.increment(1));
}
else if (userid == "1"){
DocumentReference ref = dFirestore.collection("userList").document("daddy");
ref.update("points", FieldValue.increment(1));
}
else if (userid == "2"){
DocumentReference ref = dFirestore.collection("userList").document("benjamin");
ref.update("points", FieldValue.increment(1));
}
else if (userid == "3"){
DocumentReference ref = dFirestore.collection("userList").document("gregory");
ref.update("points", FieldValue.increment(1));
}
else{
}
}
}
});
choreList.remove(position);
//Toast.makeText(getApplicationContext(), rmText, duration).show();
dFirestore.collection("choreList").document(chore_id)
.delete();
}
});
}
'''
logcat的输出没有帮助: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String,int)'
第93行:
userid = context.getSharedPreferences("com.example.choretest", context.MODE_PRIVATE).getString("userID", "");
但是该值ISNT为空,因为我在另一个Java类中对其进行了定义,并且我将其登录到其他Java类中,因此该定义为非null。起初,我认为共享首选项可能是一个错误,但是它们在MainActivity中已正确定义:
SharedPreferences prefs = this.getSharedPreferences("com.example.choretest", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("userID", selection);
editor.commit();
因此,我不知道代码有什么问题。