我正在尝试使用来自SQLite数据库内容的数据加载recyclerview。但它不起作用
这就是我所做的
活动类
public class ViewMembership extends AppCompatActivity {
private RecyclerView recyclerView;
private membership_view_recycler_adapter m;
private DBHelper dbHelper;
public List<membership_recycler_model> membershipList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_membership);
dbHelper=new DBHelper(this);
////////////////////////////////////////////////////////////////////////////
recyclerView=(RecyclerView) findViewById(R.id.View_Membership_Recycler);
m=new membership_view_recycler_adapter(membershipList);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(m);
prepare_membership();
//////////////////////////////////////////////////////////////////////////
}
public void prepare_membership()
{
System.out.println("#######################Prepare_membership called");
membershipList=dbHelper.membership_for_recycler_view();
m.notifyDataSetChanged();
}}
适配器类
public class membership_view_recycler_adapter extends RecyclerView.Adapter<membership_view_recycler_adapter.MyViewHolder> {
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name,region;
public MyViewHolder(View itemView) {
super(itemView);
name=(TextView) itemView.findViewById(R.id.membership_name_textview);
region=(TextView) itemView.findViewById(R.id.membership_region_textview);
}
}
public membership_view_recycler_adapter(List<membership_recycler_model> membership_list) {
this.membership_list = membership_list;
}
private List<membership_recycler_model> membership_list;
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.membership_view_row,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
membership_recycler_model membership=membership_list.get(position);
holder.name.setText(membership.getMembership_name());
holder.region.setText(membership.getRegion());
}
@Override
public int getItemCount() {
return membership_list.size();
}}
我没有编译错误,应用程序没有抛出任何异常。 dbHelper.membership_for_recycler_view()返回适当的值。我是Android的新手。我是在教程的帮助下完成的。我做错了什么?
答案 0 :(得分:1)
我认为这里的问题是你在呼叫prepare_membership()
稍后运行并在使用空列表之前将数据传递到适配器。尝试进行以下更改:
在适配器中添加新方法 -
public void refreshData(List<membership_recycler_model> membership_list){
this.membership_list = membership_list;
notifyDataSetChanged();
}
在prepare_membership()函数内部从db获取列表后调用此方法,即m.refreshData(membershipList)
`