在实现了保存文字的功能之后,接下来咱们要实如今主页面中的ListView中显示出咱们已经保存了的信息;既然要用ListView,则必定要有一个适配器adapter去添加内容,咱们新建立一个MyAdapter去继承BaseAdapter,使用BaseAdapter自带的getView方法在ListView中的每个Item中显示从数据库中读取到的每条信息;java
那么咱们如今思考一下我么如今所面临的问题有哪些:数据库
在ListView中的Item中显示数据的格式,须要咱们建立一个自定义的View去接受内容;须要新建一个Xml文件;ide
既然须要从数据库中读取数据后显示到ListView中,那么就要建立一个查询数据库的方法,将查询到的数据传递给adapter中处理;布局
将查询到的数据库中的每一行的数据显示到不一样的Item中;this
如今问题列出来了,就到了解决问题的时候了;url
1. 咱们先建立一个Call.xml文件,把View布局排列好,两个ImageView,一个用来显示图片的缩略图,一个用来显示视频的缩略图,两个TextView,一个用来显示内容,一个用来显示时间;spa
2. 那么如今咱们在主文件中建立一个方法,从数据库中读取数据的方法,而后将数据交给adapter处理;code
Cursor cursor; //建立一个游标 private NotesDB notesDB; //实例一个数据库对象 private SQLiteDatabase dbReader; //操做数据库读写的方法 //实例化数据库;获取数据库读的权限 notesDB=new NotesDB(this); dbReader=notesDB.getReadableDatabase(); //建立方法查询数据库! public void selectDB(){ //将数据库中的每一行数据都保存在游标中 cursor=dbReader.query(notesDB.TABLE_NAME, null, null, null, null, null, null); myAdapter=new MyAdapter(this, cursor); lv.setAdapter(myAdapter); }
3. 如今咱们处理MyAdapter中的事物,这个部分也是最麻烦的;视频
BaseAdapter中有四个重写的方法;前三个比较容易;
xml
private Context context; //将上下文传入 private Cursor cursor; //承接已经接收数据库数据信息的游标 LinearLayout layout; //将xml文件转换为一个view public MyAdapter(Context context,Cursor cursor) { // TODO Auto-generated constructor stub this.context=context; this.cursor=cursor; } @Override public int getCount() { // TODO Auto-generated method stub return cursor.getCount(); } //此方法返回游标中数据的个数 @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return cursor.getPosition(); } //此方法获得了此时操做第arg0个Item @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } //得到Item的Id
咱们将在getView方法中实现添加数据的功能;
@Override //将结果返回到activity中的listview中 public View getView(int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub //使用LayoutInflater对象将一个布局文件转换为视图; LayoutInflater inflater=LayoutInflater.from(context); layout=(LinearLayout) inflater.inflate(R.layout.cell, null); //实例化在call.xml中添加的控件; TextView contenttv=(TextView) layout.findViewById(R.id.list_content); TextView timetv=(TextView) layout.findViewById(R.id.list_time); ImageView imgtv=(ImageView) layout.findViewById(R.id.list_img); ImageView rediotv=(ImageView) layout.findViewById(R.id.list_video); cursor.moveToPosition(arg0); //游标移动到当前列 //获取内容列,将游标中当前位置的全部数据保存到变量中 String content=cursor.getString(cursor.getColumnIndex("content")); String time=cursor.getString(cursor.getColumnIndex("time")); String url=cursor.getString(cursor.getColumnIndex("path")); String video=cursor.getString(cursor.getColumnIndex("video")); contenttv.setText(content); timetv.setText(time); imgtv.setImageBitmap(“”); //这是获得图片缩略图的方法,现先省略 rediotv.setImageBitmap(“”); //这是获得视频缩略图的方法 return layout; }
在主程序中的activity的生命周期中的 protected void onResume(){}方法中,执行selectDB()方法;则能够发现保存的文字信息显示到ListView中了;