Android的SQlite的使用

Android系统集成了一个轻量级的数据库:SQlite。SQlite不像Oracle、MySQl数据库那样需要安装、启动服务器进程,SQLite数据库只是一个文件

实例1:向数据库里插入数据

主界面:

由两个输入框和一个按钮,以及一个ListView组成
在输入框输入数据,点击按钮发送,数据会送到SQLite中并且在ListView中显示出来

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <EditText
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:lines="2"
        />
    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送"
        />
    <ListView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

ListView用的样式Line.xml界面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/my_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:width="120dp"
        />
    <EditText
        android:id="@+id/my_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Java代码:

public class MainActivity extends Activity{
    SQLiteDatabase db;
    Button bn = null;
    ListView listView;
    public 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) {
                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){
                    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
        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);
    }
    public void onDestroy(){
        super.onDestroy();
        //退出程序时关闭SQLiteDatabase
        if (db != null && db.isOpen()){
            db.close();
        }
    }
}

上一个例子中在判断底层数据库是否包含newsinf数据表时使用了try,catch
也就是先尝试插入记录如果根据抛出异常,就创建news_inf数据表,再插入记录.
这样的方式其实有些繁琐,使用Android提供的SQliteOpenHelper能够处理这个问题

实例2:英语单词本

先创建SQLiteOpenHelper的子类,代码如下:

public class MyDatabaseHelper extends SQLiteOpenHelper{
    final String CREATE_TABLE_SQL =
            "create table dict(_id integer primary " +
                    "key autoincrement , word , detail)";
    public MyDatabaseHelper(Context context, String name, int version){
        super(context, name, null, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //第一次使用数据库时自动建表
        db.execSQL(CREATE_TABLE_SQL);
    }

    @Override
    //用于更新数据库时,打印一条提示的消息
    // oldversion与newVersion为数据库的旧版本与新版本
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("--------onUpdate Called--------"
         + oldVersion + "--->" + newVersion);
    }
}

可以看到这个类继承了SQLiteOpenHelper并且重写了onCreate方法,当程序第一次启动时
系统就会调用onCreate方法来初始化底层数据

如果这个类的实例传入的数据的数据库版本号高于已有的版本号,
则系统会自动调用onUpgrade方法来更新数据库。


然后来看实例的程序,主界面如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <EditText
        android:id="@+id/word"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/insert"/>
    <EditText
        android:id="@+id/key"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/search"/>
</LinearLayout>

主界面前两个输入框用来输入英文与相应的翻译,输入后点击insert按钮就将单词录入数据库

第三个输入框输入想要查询的英文,然后点击search按钮进行查询

MainActivity代码如下:

public class MainActivity extends AppCompatActivity {
    MyDatabaseHelper dbHelper;
    Button insert = null;
    Button search = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建MyDatabaseHelper对象,指定数据库版本为1
        dbHelper = new MyDatabaseHelper(this, "myDict.db3", 1);
        insert = (Button) findViewById(R.id.insert);
        search = (Button) findViewById(R.id.search);
        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String word = ((EditText)findViewById(R.id.word)).getText().toString();
                String detail = ((EditText)findViewById(R.id.detail)).getText().toString();
                //插入生词记录
                insertData(dbHelper.getReadableDatabase(), word, detail);
                Toast.makeText(MainActivity.this, "添加生词成功", Toast.LENGTH_SHORT).show();
            }
        });
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取用户输入
                String key = ((EditText)findViewById(R.id.key)).getText().toString();
                //执行查询
                Cursor cursor = dbHelper.getReadableDatabase().rawQuery(
                        "select * from dict where word like ? or detail like ?",
                        new String[] {"%" + key + "%", "%" + key + "%"});
                //创建一个Bundle对象
                Bundle data = new Bundle();
                data.putSerializable("data", converCursorTolist(cursor));
                //创建一个Intent
                Intent intent = new Intent(MainActivity.this, ResultActivity.class);
                intent.putExtras(data);
                startActivity(intent);
            }
        });
    }
    protected ArrayList<Map<String, String>>
    converCursorTolist(Cursor cursor){
        ArrayList<Map<String, String>> result = new ArrayList<Map<String,String>>();
        //遍历Cursor结果集
        while (cursor.moveToNext())
        {
            Map<String, String> map = new HashMap<>();
            map.put("word", cursor.getString(1));
            map.put("detail", cursor.getString(2));
            result .add(map);
        }
        return result;
    }
    private void insertData(SQLiteDatabase db, String word, String detail) {
        //执行插入语句
        db.execSQL("insert into dict values(null , ? , ?)"
        , new String[]{word, detail });
    }

    public void onDestroy(){
        //退出程序时关闭数据库
        super.onDestroy();
        if (dbHelper != null){
            dbHelper.close();
        }
    }
}

这个程序点击查询按钮时会跳转到ResultActivity,代码如下:

public class ResultActivity extends Activity {
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup);
        ListView listView = (ListView) findViewById(R.id.show);
        Intent intent = getIntent();
        //获取intent所携带的数据
        Bundle data = intent.getExtras();
        List<Map<String, String>> list = (List<Map<String, String>>)data.getSerializable("data");
        //将List封装成SimpleAdapter
        SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this
        , list,
                R.layout.line, new String[]{ "word", "detail" }
        , new int[] {R.id.word, R.id.detail});
        //填充ListView
        listView.setAdapter(adapter);
    }
}

猜你喜欢

转载自www.cnblogs.com/vonzc/p/10601637.html