使用SQL语句操作SQLite数据库

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。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值