Android Development Series (17): Read the database file under the Assets folder

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 has overcome a problem with a small game written in my previous blog.) Also able to read the database files under the raw folder)

This creates a problem. This problem is actually very well solved, such as the following:

We first put the database file with the data in the Assets resource folder below, and then when the APK application starts, the assets folder of the database file data into the memory of the real machine.



Let's start our code writing below:

First of all. We built a Datab Android project named Datab, and we posted the folder view of project:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmdgwmduzma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

We'll start by creating a database that can be created with SQL statements in Databactivity.java and then insert a few data. Then put the created and inserted data database into the assets directory below.

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

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmdgwmduzma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Can see. We inserted three data in the test.db.


Next, we are going to read the database under the Assets folder 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 folder and then write to SDcard, Assumed to exist in the sdcard. Just open the database and copy the past from the assets folder without being present * @author Big_adamapple * */public class SQLDM {//Database storage path String FilePath = "data/      Data/com.datab.cn/test.db ";            The database holds the folder Data/data/com.main.jh the following 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);                      }//Last Close will be able to fos.flush ();                      Fos.close ();                  Is.close (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ()                      ;                return null; }//Assuming that there is no database we have written him on the SD card.              You can then run this method once to return to the database with 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, very easy. I understand it at the first glance.

And then. Let's see what our interface looks like on a virtual machine:


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmdgwmduzma==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Can see, we have the data in the database, then we can put the Bin folder under 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 folder

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.