我希望从android数据库显示数据。这里我使用的是回收站视图。参考代码为http://www.androidhive.info/2016/01/android-working-with-recycler-view/。我的代码如下所示。
SpeedDialViewActivity.java
public class SpeedDialViewActivity extends AppCompatActivity {
private List<Bean> beanList = new ArrayList<>();
private RecyclerView recyclerView;
private ViewAdapter mAdapter;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_dial_view);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new ViewAdapter(beanList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareData();
}
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
Bean bean;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
/* bean = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial());
beanList.add(bean);
}*/
/* Bean bean = new Bean("Mad Max: Fury Road", "Action & Adventure", "2015");
beanList.add(bean);
bean = new Bean("Inside Out", "Animation, Kids & Family", "2015");
beanList.add(bean);
bean = new Bean("Inside Out", "Animation, Kids & Family", "2015");
beanList.add(bean);
bean = new Bean("Inside Out", "Animation, Kids & Family", "2015");
beanList.add(bean);*/
}
}
在prepareData()方法中,我可以在日志中打印答案。但我不能在我的活动中显示。请帮帮我。
答案 0 :(得分:1)
您可以使用cursoradapter从数据库加载数据,并在您的recyclerview中使用视图持有者显示它。
答案 1 :(得分:0)
要在列表中显示数据库中的数据,您可以使用CursorAdapter
。只需创建一个Cursor,就可以让他完成这项工作。
一个简单的例子如下:
DatabaseHandler handler = new DatabaseHandler(this);
SQLiteDatabase db = handler.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT first_name, last_name FROM person", null);
然后,将此光标传递给适配器:
ListView lvItems = (ListView) findViewById(R.id.lvItems);
MyCursorAdapter adapter = new TodoCursorAdapter(this, cursor);
lvItems.setAdapter(adapter);
复杂的部分是根据需要实现CursorAdapter。这是构建视图和读取光标的视图。 <{1}}将调用每一行。
BindView
在这里,你有一个小例子,你只需要生成Layout(只需两个TextView)来匹配我写的cursorAdapter。
source我曾经生成过这个小例子。你会发现比这里更多的信息。
答案 2 :(得分:-1)
我通过添加prepareData()
List<Bean> beanList = handler.getAllContacts();
方法
我使用mAdapter.notifyDataSetChanged();
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
this.beanList.addAll(beanList);
mAdapter.notifyDataSetChanged();
}