日期:2014-05-16  浏览次数:20534 次

Android开发—数据库应用—访问数据表(SQLite OpenHelper) —添加查询

/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:数据库应用—添加查询

* 作 者: 雷恒鑫
* 完成日期: 2012 年 08 月 14 日
* 版 本 号: V1.0
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:

* 程序头部的注释结束

*/

 

方法:在“NotesDbAdapter”类中新增一个“getall”方法来查询“notes”数据表中的所有数据,修改后的“DummyNote.java”文件如下:

package com.demo.android.dummynote;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.content.Intent;
import android.widget.ListView;


public class DummyNote extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Tell the list view which view to display when the list is empty
        getListView().setEmptyView(findViewById(R.id.empty));
        setAdapter();
    }
    private String[] note_array = {
    		"gasolin",
    		"crota",
    		"louk",
    		"magicion"
    }; 
    private NotesDbAdapter mDbHelper;
    private Cursor mNotesCursor;
    private void setAdapter(){
    	mDbHelper = new NotesDbAdapter(this);
    	mDbHelper.open();
    	fillData();
    }
    private void fillData(){
    	mNotesCursor = mDbHelper.getall();
    	startManagingCursor(mNotesCursor);
    	
    	//Create an array to specify the field we want to display in the list
    	String[] from = new String[]{NotesDbAdapter.KEY_NOTE};
    	
    	//an array of the fields we want to bind those fields to
    	int[] to = new int[]{android.R.id.text1};
    	
    	//Now create a simple cursor adapter
    	SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
    			android.R.layout.simple_list_item_1,mNotesCursor,from,to);
    	setListAdapter(adapter);
    }
}


修改后的“DummyDbAdapter.java”文件如下:

 

package com.demo.android.dummynote;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorF