public class MainActivity extends Activity {
SQLiteDatabase db;
Button bn=null;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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 View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//获取用户输入
String
title=((EditText)findViewById(R.id.title)).getText().toString();
String
content=((EditText)findViewById(R.id.content)).getText()+"";
try{
insertData(db,title,content);
Cursor cursor=db.rawQuery("select * from news_inf",
null);
inflateList(cursor);
}catch(SQLException 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);
}
}
});
}
protected void inflateList(Cursor cursor) {
// TODO Auto-generated method stub
//填充SimpleCursorAdapter
SimpleCursorAdapter adapter=new
SimpleCursorAdapter(MainActivity.this, R.layout.line, cursor, new
String[]{"news_title","news_content"}, new
int[]{R.id.my_title,R.id.my_content});
//显示数据
listView.setAdapter(adapter);
}
protected void insertData(SQLiteDatabase db2, String title,
String content) {
// TODO Auto-generated method stub
//执行插入语句
db2.execSQL("insert into news_inf values(null,?,?)", new
String[]{title,content});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//退出程序时关闭SQLiteDatabase
if(db!=null&&db.isOpen()){
db.close();
}
}
}