Android copy Database to sd card (online collection, unauthenticated)

Source: Internet
Author: User
Tags name database

Use SQLite in Android, copy database from assets to SD card, support files larger than 1M

If you use an SD card, you need to set permissions in Androidmanifest.xml

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS" ></uses-permission>

1 package Cn.arthur.common;
2
3 Import Java.io.File;
4 Import Java.io.FileOutputStream;
5 Import java.io.IOException;
6 Import Java.io.InputStream;
7 Import Java.io.OutputStream;
8
9 Import Android.content.Context;
Ten import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
Import android.database.sqlite.SQLiteException;
Import Android.database.sqlite.SQLiteOpenHelper;
14
15/**
* @author Joshua
17 * Usage:
* DBHelper dbhelper = new DBHelper (this);
* Dbhelper.createdatabase ();
* Sqlitedatabase db = Dbhelper.getwritabledatabase ();
* Cursor cursor = db.query ()
* Db.execsql (sqlString);
23 * Note: Execsql does not support bands; multiple SQL statements can only be executed one line at a time.
24 * See Execsql Source Comments (multiple statements separated by; S is not supported.)
25 * The database file under assets will be copied directly to Db_path, but the database file size is limited to 1M
26 * If there is more than 1M of large files, you need to first split into n small files, and then use Copybigdatabase () to replace copydatabase ()
27 */
-public class DBHelper extends Sqliteopenhelper {
29//version of the user database file
private static final int db_version = 1;
31//Database file target storage path is the default location of the system, Cn.arthur.examples is your package name
The private static String Db_path = "/data/data/cn.arthur.examples/databases/";
33/*
34//If you want to store the database file on the SD card
private static String Db_path = Android.os.Environment.getExternalStorageDirectory (). GetAbsolutePath ()
+ "/arthurcn/drivertest/packfiles/";
37 */
$ private static String db_name = "hello.db";
Assets_name private static String = "Hello.db";
40
Sqlitedatabase private myDataBase = null;
Private final Context Mycontext;
43
44/**
45 * If the database file is large, use Filesplit to split smaller files smaller than 1M
46 * Split in this example into hello.db.101 hello.db.102 hello.db.103
47 */
48//First file name suffix
$ private static final int assets_suffix_begin = 101;
50//last filename suffix
Wuyi private static final int assets_suffix_end = 103;
52
53/**
54 * In Sqliteopenhelper subclasses, you must have this constructor
@param context Context Object
* @param name database names
Factory * @param is generally null
* * @param version of the current database, the value must be an integer and an incremented state
59 */
Public DBHelper (Context context, String name, Cursorfactory factory, int version) {
61//The constructor in the parent class must be called through Super
+ Super (context, name, null, version);
This.mycontext = context;
64}
65
DBHelper Public (context context, String name, int version) {
(context,name,null,version);
68}
69
DBHelper Public (context context, String name) {
(context,name,db_version);
72}
73
DBHelper Public (context context) {
(Context, Db_path + db_name);
76}
77
All public void CreateDatabase () throws ioexception{
Dbexist Boolean = Checkdatabase ();
if (dbexist) {
81//Database already exists, do nothing.
}else{
83//CREATE DATABASE
try {
The file dir = new file (Db_path);
if (!dir.exists ()) {
Dir.mkdirs ();
88}
The file DBF = new file (Db_path + db_name);
if (dbf.exists ()) {
Dbf.delete ();
92}
Sqlitedatabase.openorcreatedatabase (DBF, NULL);
94//Copy the db file in Asseets to Db_path
Copydatabase ();
(IOException e) {
$ throw new Error ("Database creation failed");
98}
99}
100}
101
102//Check whether the database is valid
103 Private Boolean checkdatabase () {
104 Sqlitedatabase CheckDB = null;
MyPath String = Db_path + db_name;
106 try{
107 CheckDB = Sqlitedatabase.opendatabase (MyPath, NULL, sqlitedatabase.open_readonly);
108}catch (Sqliteexception e) {
109//database does ' t exist yet.
110}
111 if (CheckDB! = null) {
Checkdb.close ();
113}
return CheckDB! = null? True:false;
115}
116
117/**
118 * Copies your database from your local assets-folder to the just created empty database in the
119 * System folder, from where it can be accessed and handled.
* This was done by transfering ByteStream.
121 * * *
122 private void Copydatabase () throws ioexception{
123//open your local db as the input stream
124 InputStream myinput = Mycontext.getassets (). open (Assets_name);
//Path to the just created empty db
126 String Outfilename = Db_path + db_name;
127//open The empty DB as the output stream
OutputStream myoutput = new FileOutputStream (outfilename);
129//transfer bytes from the inputfile to the OutputFile
byte[] buffer = new byte[1024];
131 int length;
(length = myinput.read (buffer)) >0) {
133 myoutput.write (buffer, 0, length);
134}
135//close The Streams
136 Myoutput.flush ();
137 myoutput.close ();
138 Myinput.close ();
139}
140
141//Copy the large database file under assets with this
142 private void Copybigdatabase () throws ioexception{
143 InputStream Myinput;
144 String Outfilename = Db_path + db_name;
145 OutputStream myoutput = new FileOutputStream (outfilename);
146 for (int i = assets_suffix_begin; i < assets_suffix_end+1; i++) {
147 myinput = Mycontext.getassets (). Open (Assets_name + "." + i);
148 byte[] buffer = new byte[1024];
149 int length;
(length = myinput.read (buffer)) >0) {
151 myoutput.write (buffer, 0, length);
152}
153 Myoutput.flush ();
154 Myinput.close ();
155}
156 Myoutput.close ();
157}
158
159 @Override
synchronized void Close () {
161 if (myDataBase! = null) {
162 Mydatabase.close ();
163}
164 Super.close ();
165}
166
167/**
168 * This function is executed at the time of the first creation,
169 * This method is actually called the first time you get the Sqlitedatabase object
170 */
171 @Override
172 public void OnCreate (Sqlitedatabase db) {
173}
174
175/**
176 * The database table structure changes when using
177 */
178 @Override
179 public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
180}
181
182}
183

===============================

Copy the resource file under assets in Android to SD card (can exceed 1M)

Original: http://www.cnblogs.com/wainiwann/p/3274386.html

Many mobile games, after installing the APK, you need to download the appropriate resource pack before you can enter the game.

There is a requirement: the resource bundle that is needed in the game is hit within the APK, and installed on the phone with the APK.

This is not necessary, after installing the APK, go to download the resources. (So the size of the APK will be larger)

So on the internet began to find the corresponding direct access with the APK installed on the phone with the resources. For example, a "test.zip" resource is placed under the assets directory. When the APK is installed, I may need to access this "test.zip" resource file. (Maybe I'm going to unzip it somewhere)

On the internet for a long time, said what in the assets under the resources how can not more than 1M, or to be divided into a number of less than 1M of small files, and then use the time in a large file, say what to use what database. In short, the feeling is not a useful one.

Then I realized a function of copying resources from assets to SD card. There is no limit to copying to the SD card.

The reason to copy it is because the resources within the assets are not accessible after the APK is installed. So you want to copy it to an easy-to-access place. For example, a assets is a zip file that needs to be decompressed after installation. And I want to use Ant.jar (support encoding) when extracting. So I'm going to copy the zip resource to a place and then unzip it.

The following code:

private void Copybigdatatosd (String stroutfilename) throws IOException     {          inputstream myinput;          OutputStream myoutput = new FileOutputStream (stroutfilename);          Myinput = This.getassets (). Open ("Yphone.zip");          byte[] buffer = new byte[1024];          int length = myinput.read (buffer);        while (length > 0)        {            myoutput.write (buffer, 0, length);             Length = myinput.read (buffer);        }                Myoutput.flush ();          Myinput.close ();          Myoutput.close ();            }  

Note: The parameter is the destination to be copied such as "/mnt/sdcard/test/out.zip";

Here "Myinput = Cgameactivity.getassets (). Open (" Yphone.zip "); "Open is the name of the resource you put under assets." This example puts a file called "Yphone.zip";

During the test, it is found that when the resource file is large, such as about 200M, it may be an error.

But it's guaranteed to be 100M a bit, no problem.

Finally, this function requires permission to run!

Android Copy Database to sd card (online collection, unauthenticated)

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.