在實現了保存文字的功能之後,接下來咱們要實如今主頁面中的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中了;