适配器崩溃,方法为getItemCount nullpointer

时间:2018-12-26 17:46:16

标签: java android nullpointerexception

当我以调试模式运行项目时,它不会出现问题,但是当我挤入普通的android studio模式时,它会崩溃。

我的适配器

<!DOCTYPE html>
<html>
<body>

<h2>Make a table based on JSON data.</h2>

<p id="demo"></p>

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "name", limit: 50 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    myObj = JSON.parse(this.responseText);
    txt += "<table border='1'>"
    for (x in myObj) {
      txt += "<tr><td>" + myObj[x].name + "</td></tr>";
    }

    txt += "</table>"    
    document.getElementById("demo").innerHTML = txt;
  }
};
xmlhttp.open("GET", "http://infoportal.vag.de/InfoPortal/busstations.xhr", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send("x=" + dbParam);
</script>

</body>
</html>

}

我的片段

public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.ViewHolder> {
Context context;
Screen screen;

public InfoAdapter(Context context, Screen screen) {
    this.context = context;
    this.screen = screen;
}

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

@Override
public void onBindViewHolder(@NonNull InfoAdapter.ViewHolder holder, int position) {
    holder.name.setText(screen.getInfo().get(position).getName());
    holder.data.setText(screen.getInfo().get(position).getData());

}

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

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView name, data;

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

        name = view.findViewById(R.id.name);
        data = view.findViewById(R.id.data);
    }
}

}

java.lang.NullPointerException:尝试在空对象引用上调用接口方法'int java.util.List.size()'     在com.example.allan.santanderapp.adapter.InfoAdapter.getItemCount(InfoAdapter.java:41)

1 个答案:

答案 0 :(得分:0)

异常消息非常清楚。

也许您没有在Screen对象中填充其信息列表,这就是infos为null的原因,而您正在尝试在该null对象上调用方法size()

请在处理屏幕对象时显示。