CREATE TABLE user ( name TEXT ); INSERT INTO user VALUES ('letian'); INSERT INTO user VALUES ('xiaoming');
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="獲取數據庫內容" /> </LinearLayout>
package com.example.initsqlite; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/com.example.initsqlite/databases/"; String DB_NAME = "appdata.db"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getSqliteContent(); } }); } /** * 獲取數據庫信息 */ public void getSqliteContent(){ File f = new File(DB_PATH + DB_NAME); if (!f.exists()) { prepareDB(); } Toast.makeText(MainActivity.this, "獲取數據庫內容", Toast.LENGTH_SHORT).show(); SQLiteDatabase db = openOrCreateDatabase(DB_PATH+DB_NAME, Context.MODE_PRIVATE, null); Cursor c = db.rawQuery("SELECT NAME FROM user", new String[]{}); String result = ""; while (c.moveToNext()) { String name = c.getString(c.getColumnIndex("name")); result = result + name + "\n"; } Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); } /** * 準備數據庫 */ public void prepareDB() { if ((new File(DB_PATH+DB_NAME)).exists() == false) { Toast.makeText(MainActivity.this, "檢查到沒有數據庫,準備數據庫ing", Toast.LENGTH_SHORT).show(); // 如 SQLite 數據庫文件不存在,再檢查一下 database 目錄是否存在 File f = new File(DB_PATH); // 如 database 目錄不存在,新建該目錄 if (!f.exists()) { f.mkdir(); } try { // 獲得 assets 目錄下咱們實現準備好的 SQLite 數據庫做爲輸入流 InputStream is = getAssets().open(DB_NAME); // 輸出流 OutputStream os = new FileOutputStream(DB_PATH + DB_NAME); // 文件寫入 byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } // 關閉文件流 os.flush(); os.close(); is.close(); Toast.makeText(MainActivity.this, "數據庫已經準備好啦", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(MainActivity.this, "數據庫已經存在", Toast.LENGTH_SHORT).show(); } } }
第一次點擊「獲取數據庫內容「這個按鈕時,程序會依次經過Toast依次顯示: html
檢查到沒有數據庫,準備數據庫ing
數據庫已經準備好啦
獲取數據庫內容
letian xiaoming
獲取數據庫內容
letian xiaoming