Android 程式開發:(十九)資料庫 —— 19.3 預建立資料庫

來源:互聯網
上載者:User

在開發過程中,有時候,預先建立好資料庫比在程式運行時建立資料庫更加地高效。舉個例子,你想編寫一個程式,這個程式把你去過的地方的座標都顯示出來。這種情況下,預先建立資料庫是更加容易的,比在運行時建立資料庫。

這裡,需要使用一些免費的工具。推薦使用SQLite Database Browser,支援多平台,並且免費。: http://sourceforge.net/projects/sqlitebrowser/

下面是建立一個連絡人表的例子。

在設計階段把資料庫建好,下一步,就是把資料庫和程式捆綁在一起,這樣,在運行時,就能使用資料庫了。

1. 把資料庫放在assets檔案夾下面。

2. 把assets檔案夾下面的資料庫,複製到程式的安裝路徑下。

public class DatabasesActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        DBAdapter db = new DBAdapter(this);                try {            String destPath = "/data/data/" + getPackageName() +                "/databases";            File f = new File(destPath);            if (!f.exists()) {                          f.mkdirs();                f.createNewFile();                          //---copy the db from the assets folder into              // the databases folder---                CopyDB(getBaseContext().getAssets().open("mydb"),                    new FileOutputStream(destPath + "/MyDB"));            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }               //---get all contacts---        db.open();        Cursor c = db.getAllContacts();        if (c.moveToFirst())        {            do {                DisplayContact(c);            } while (c.moveToNext());        }        db.close();    }        public void CopyDB(InputStream inputStream,     OutputStream outputStream) throws IOException {        //---copy 1K bytes at a time---        byte[] buffer = new byte[1024];        int length;        while ((length = inputStream.read(buffer)) > 0) {            outputStream.write(buffer, 0, length);        }        inputStream.close();        outputStream.close();    }    public void DisplayContact(Cursor c)    {        Toast.makeText(this,                "id: " + c.getString(0) + "\n" +                "Name: " + c.getString(1) + "\n" +                "Email:  " + c.getString(2),                Toast.LENGTH_LONG).show();    }}

3. 調試,用DDMS查看,資料庫被複製到了指定的位置。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.