一、先检查适配器#####
查看适配器是否有误,
检查getItemCount()
方法中是否 return data.size();
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<String> data = new ArrayList<>();
private Context context;
private LayoutInflater inflater;
public RecyclerViewAdapter(Context context, List<String> data) {
this.data = data;
this.context = context;
inflater=LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.recycler_view_item,null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.tv.setText(data.get(position));
}
@Override
public int getItemCount() {
return data.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView tv;
public ViewHolder(View view) {
super(view);
tv=(TextView) view.findViewById(R.id.tv_item);
}
}
}
二、无数据#####
启动发现有错,指向adapter中的getItemCount()方法,并报了一个空指针异常,说明没有数据
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at wapchief.top.retrofitrxjavatest.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:47)
三、布局管理器配置#####
在onCreate方法中实现:
//数据源
datas();
adapter=new RecyclerViewAdapter(this,data);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
四、onCreate方法#####
对比两种方法,
如果在onCreate(Bundle savedInstanceState, PersistableBundle persistentState)
中使用
需要在AndroidManifest.xml文件下Activity中注册权限:
<activity android:name=".RecyclerViewActivity"
android:persistableMode="persistAcrossReboots"/>
在onCreate(Bundle savedInstanceState)
中则不需要
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);