Android Development Series (17): Read the database file under the assets directory

Source: Internet
Author: User

When it comes to Android applications, the database is inevitably used. But when we deploy the app's apk to the real machine, the database that has been created and the data inside it cannot be installed on the real machine with the APK.

(PS: This blog solves a problem of a small game written in my previous blog, but also can read the database files in the raw directory)

This creates a problem that is in fact a good solution and the solution is as follows:

We first put the database file with the data in the Assets Resource directory, and then when the APK application starts, the database files in the assets directory are written to the memory of the real machine.



Let's start by writing our code below:

First, we build a datab Android project named Datab, and we post the catalog view of the project:


We first create a database that can be created in Databactivity.java with SQL statements and then insert a few data. Then put the created and inserted database into the assets folder below.

Let's look at the structure of the TEST.DB database I put in:


As you can see, we have inserted three data in the test.db.


Next, we are going to read the database in the assets directory when the app starts, and then write test.db to the SDcard data/data/com.datab.cn path below.

We first create a new class: Sqldm.java:

<span style= "FONT-SIZE:18PX;" >package com.datab.cn;import java.io.file;import Java.io.fileoutputstream;import java.io.IOException;import Java.io.inputstream;import Android.content.context;import Android.content.res.assetmanager;import Android.database.sqlite.sqlitedatabase;import android.util.log;/** * This class is implemented to read the database file from the assets directory and then write to SDcard, If it exists in SDcard, open the database, copy the past from the assets directory without being present * @author Big_adamapple * */public class SQLDM {//Database storage path String Filep      Ath = "data/data/com.datab.cn/test.db";            The database holds the folder Data/data/com.main.jh below String pathstr = "data/data/com.datab.cn";       Sqlitedatabase database;          Public Sqlitedatabase OpenDatabase (context context) {System.out.println ("FilePath:" +filepath);              File Jhpath=new file (FilePath);                See if the database file exists if (jhpath.exists ()) {log.i ("test", "existence database");            exists returns Sqlitedatabase.openorcreatedatabase (Jhpath, NULL) directly to the open database;  }else{//Does not exist first create folder file Path=new file (PATHSTR);                LOG.I ("Test", "pathstr=" +path);                 if (Path.mkdir ()) {log.i ("test", "Create succeeded");                }else{log.i ("Test", "Create failed");                  };                      try {//Get resources Assetmanager am= context.getassets ();                      Get the input stream of the database InputStream Is=am.open ("test.db");                    LOG.I ("Test", is+ "");                      Write to sdcard with output stream above FileOutputStream fos=new fileoutputstream (Jhpath);                    LOG.I ("Test", "fos=" +fos);                    LOG.I ("Test", "jhpath=" +jhpath);                      Create a byte array for 1KB write once byte[] Buffer=new byte[1024];                      int count = 0;                        while ((count = is.read (buffer)) >0) {log.i ("test", "get"); Fos.writE (Buffer,0,count);                      }//The Last Close will be Fos.flush ();                      Fos.close ();                  Is.close (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ()                      ;                return null;              }//If you do not have this database we have written him to the SD card, and then in the execution of this method can be returned to the database return OpenDatabase (context); }}}</span>

Then, we get the data in the database in Databactivity.java:

<span style= "FONT-SIZE:18PX;" >package Com.datab.cn;import Android.app.activity;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.os.bundle;import Android.widget.textview;public Class Databactivity extends activity {/** Called when the activity is first created. */@Override public void OnCreate (Bundle savedinstancestate)        {super.oncreate (savedinstancestate);                Setcontentview (R.layout.main);        Open the database output stream SQLDM s = new SQLDM ();                 Sqlitedatabase db =s.opendatabase (Getapplicationcontext ());        TextView TEXTV = (TextView) Findviewbyid (R.ID.TEXTV);         Querying testid=1 data in the database cursor cursor = db.rawquery ("select * from Testbiao where testid=?", New string[]{"1"});        String name = NULL;        if (Cursor.movetofirst ()) {name = Cursor.getstring (Cursor.getcolumnindex ("name"));        }//This is a textview that displays the name of the resulting database.        Textv.settext (name); CurSor.close (); }}</span>
Our Main.xml view is also posted out, very simple, one can understand.

Then we'll look at what our interface looks like on a virtual machine:




We can see that we have the data in the database, then you can put the bin directory of the apk file into the real machine test, still get the data in the database

Android Development Series (17): Read the database file under the assets directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.