SQLiteDatabase存取字符串

来源:互联网 发布:程序员 必备 硬件 编辑:程序博客网 时间:2024/05/21 06:56
public class DBTest extends Activity{SQLiteDatabase db;Button bn = null;ListView listView;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);//创建或打开数据库(此处需要使用绝对路径)db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString() + "/my.db3" , null);listView = (ListView)findViewById(R.id.show);bn = (Button)findViewById(R.id.ok);bn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View source){//获取用户输入String title = ((EditText)findViewById(R.id.title)).getText().toString();String content = ((EditText)findViewById(R.id.content)).getText().toString();try {insertData(db , title , content);//执行一个带占位符的查询Cursor cursor = db.rawQuery("select * from news_inf", null);inflateList(cursor);}catch(SQLiteException  se){//执行DDL创建数据表db.execSQL("create table news_inf(_id integer primary key autoincrement,"+ " news_title varchar(50),"+ " news_content varchar(255))");//执行insert语句插入数据insertData(db , title , content);//执行查询Cursor cursor = db.rawQuery("select * from news_inf", null);inflateList(cursor);}}});}private void insertData(SQLiteDatabase db, String title , String content){//执行插入语句db.execSQL("insert into news_inf values(null , ? , ?)", new String[]{title , content});}private void inflateList(Cursor cursor){//填充SimpleCursorAdapterSimpleCursorAdapter adapter = new SimpleCursorAdapter(DBTest.this , R.layout.line, cursor , new String[]{"news_title" , "news_content"}, new int[]{R.id.my_title , R.id.my_content});//显示数据listView.setAdapter(adapter);}@Overridepublic void onDestroy(){super.onDestroy();//退出程序时关闭SQLiteDatabaseif (db != null && db.isOpen()){db.close();}}}


原创粉丝点击