您的位置:首页 > 数据库

使用SQL语句操作SQLite数据库

2016-08-12 11:55 344 查看
public class MainActivity extends Activity
{
private SQLiteDatabase db;
private 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);
Button button = (Button) findViewById(R.id.ok);
listView = (ListView) findViewById(R.id.listView);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String title = ((EditText) findViewById(R.id.titleName)).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 e)
{
db.execSQL("create table news_inf(_id integer" + " primary key autoincrement,"
+ " news_title varchar(50)," +
" news_content varchar(255))");
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)
{
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},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(adapter);
}

@Override
protected void onDestroy()
{
super.onDestroy();
if(db != null && db.isOpen())
{
db.close();
}
}
}
需要指出的是,使用SimpleCursorAdapter封装Cursor时要求底层数据主键列的列名为_id,因为SimpleCursor只能识别列名为_id的主键,否则就会出现java.lang.IllegalArgumentException。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: