最近几天,我学会了如何使用SQLiteOpenHelper创建SQLite数据库并通过RecyclerView显示它。是的,通过谷歌和Stack-overflow的力量,我已经很好地学习了它。但是,我现在通过回收器视图显示外部数据库数据时遇到了一些麻烦。最近两天我搜索了很多,大多数只是通过使用"资产文件夹和SQLiteAssetsHelper"将外部数据库导入应用程序。那么,您能否给我一些通过回收器视图显示外部SQLite数据库数据的指南?任何链接或任何书籍或任何参考资料将不胜感激。提前谢谢。
作为与数据库交互的结果,use 应该获取一个数据集(数组或像 ArrayList 这样的集合(。正如我所看到的,从您的解释中,您现在知道如何获取它,但不知道如何将其传递给您的回收器View。所以你需要一个适配器来做到这一点。适配器是一个类,将从数组数据集中获取每个对象,并从其数据中创建(膨胀(单个回收器视图项。处理完所有数组项后,适配器将生成一个项列表,这样它将用数据填充回收器视图,下面是一个代码片段,可以帮助您了解它的工作原理:
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView textView;
public MyViewHolder(TextView v) {
super(v);
textView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
TextView v = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
...
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.textView.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}
}
public class MyActivity extends Activity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true);
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
recyclerView.setAdapter(mAdapter);
}
// ...
}