我有一个 RecyclerView ,可以从Firebase数据库中获取数据。当RecyclerView到达数据源的末尾时,应用程序崩溃,如下所示:
Logcat文件:
09-27 15:30:12.826 30184-30184/com.pctoolmanconsulting.trackmyweight E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pctoolmanconsulting.trackmyweight, PID: 30184
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.startsWith(java.lang.String)' on a null object reference
at com.pctoolmanconsulting.trackmyweight.ProgressViewHolder.bind(ProgressViewHolder.java:40)
at com.pctoolmanconsulting.trackmyweight.ProgressAdapter.onBindViewHolder(ProgressAdapter.java:41)
at com.pctoolmanconsulting.trackmyweight.ProgressAdapter.onBindViewHolder(ProgressAdapter.java:15)
我无法弄清楚我应该检查空值的位置。在我的 ViewHolder 类的bind方法中或在适配器类中。
有人可以帮助我指出正确的方向吗? 感谢。
我的ViewHolder 绑定方法:
public void bind (ImageProgress progress){
name.setText(progress.name);
if(progress.progressDetail.startsWith("https://firebasestorage.googleapis.com/") || progress.progressDetail.startsWith("content://")){
progressDetailMessage.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
Glide.with(activity).load(progress.progressDetail).fitCenter().into(image);
} else {
progressDetailMessage.setVisibility(View.VISIBLE);
image.setVisibility(View.GONE);
progressDetailMessage.setText(progress.progressDetail);
}
}
适配器类:
public class ProgressAdapter extends RecyclerView.Adapter<ProgressViewHolder> {
private static final String TAG ="ProgressAdapter";
private final Activity activity;
List<ImageProgress> progressDetails = new ArrayList<>();
public ProgressAdapter(Activity activity){
this.activity = activity;
}
public void addProgress(ImageProgress progress){
progressDetails.add(progress);
notifyItemInserted(progressDetails.size());
}
@Override
public ProgressViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
return new ProgressViewHolder(activity, activity.getLayoutInflater().inflate(android.R.layout.two_line_list_item,
parent, false));
}
@Override
public void onBindViewHolder(ProgressViewHolder holder, int position){
holder.bind(progressDetails.get(position));
}
@Override
public int getItemCount() {
return progressDetails.size();
}
}
答案 0 :(得分:3)
就像其他人说的那样,你应该先检查一下null。滚动到最后一个项目时,progressDetail必须为null。
让我告诉你如何找到这个:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.startsWith(java.lang.String)' on a null object reference
查看错误所说的内容&#39;尝试调用虚拟方法&#34; startsWith&#34;&#39;,您可能会想到以哪种方法“启动”&#39;是。在阅读错误消息后检查您的代码,您会注意到&#39; startsWith&#39;在一个对象上被调用了进程详细信息&#39;这是空的!!
好的,一切都清楚。您应该检查null以避免异常。
BUT !!!最重要的是你应该知道为什么它是空的。