├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── libs │ └── jxl-2.6.9.jar ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── zsj │ │ └── filetodbdemo │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ ├── VocabularyInfoCfg.db │ │ ├── extra_voice_data.xls │ │ ├── testdata │ │ │ ├── test1.txt │ │ │ ├── test10.txt │ │ │ ├── test2.txt │ │ │ ├── test3.txt │ │ │ ├── test4.txt │ │ │ ├── test5.txt │ │ │ ├── test6.txt │ │ │ ├── test7.txt │ │ │ ├── test8.txt │ │ │ └── test9.txt │ │ └── wordlist.xls │ ├── java │ │ └── com │ │ │ └── zsj │ │ │ └── filetodbdemo │ │ │ ├── MainActivity.java │ │ │ ├── assetsdb │ │ │ └── GetWordInfoAsynTask.java │ │ │ ├── assetsfiles │ │ │ ├── AssetsFileAsynTask.java │ │ │ ├── AssetsFileDBHelper.java │ │ │ ├── AssetsFileDBManager.java │ │ │ └── AssetsFileInfo.java │ │ │ ├── excel │ │ │ ├── extravoice │ │ │ │ ├── ExtraVoiceAsynTask.java │ │ │ │ ├── ExtraVoiceDBHelper.java │ │ │ │ ├── ExtraVoiceDBManager.java │ │ │ │ └── ExtraVoiceInfo.java │ │ │ └── vocabulary │ │ │ │ ├── VocabularyAsynTask.java │ │ │ │ ├── VocabularyDBHelper.java │ │ │ │ ├── VocabularyDBManager.java │ │ │ │ └── VocabularyInfo.java │ │ │ └── util │ │ │ ├── AssetsDatabaseManager.java │ │ │ ├── CopyDbFromAsset.java │ │ │ ├── ListUtils.java │ │ │ └── PreferencesUtils.java │ └── res │ │ ├── layout │ │ ├── activity_main.xml │ │ └── content_main.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── zsj │ └── filetodbdemo │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FileToDbDemo 2 | 1、把excel文件写进数据库 3 | 2、读取assets里db数据 4 | 3、把assets里的文件写入数据库 5 | 4、把assets里的db文件拷贝到数据库 -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion "26.0.1" 6 | defaultConfig { 7 | applicationId "com.zsj.filetodbdemo" 8 | minSdkVersion 15 9 | targetSdkVersion 26 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile 'com.android.support:appcompat-v7:26.+' 28 | compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7' 29 | compile 'com.android.support:design:26.+' 30 | testCompile 'junit:junit:4.12' 31 | } 32 | -------------------------------------------------------------------------------- /app/libs/jxl-2.6.9.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangshao45612/FileToDbDemo/7a4e5a7b7116a9026523d153132d5c59e74f778f/app/libs/jxl-2.6.9.jar -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in E:\Android_studio_SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/zsj/filetodbdemo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.zsj.exceldemo", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/src/main/assets/VocabularyInfoCfg.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangshao45612/FileToDbDemo/7a4e5a7b7116a9026523d153132d5c59e74f778f/app/src/main/assets/VocabularyInfoCfg.db -------------------------------------------------------------------------------- /app/src/main/assets/extra_voice_data.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangshao45612/FileToDbDemo/7a4e5a7b7116a9026523d153132d5c59e74f778f/app/src/main/assets/extra_voice_data.xls -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test1.txt: -------------------------------------------------------------------------------- 1 | 1234567899876543210 kjfpoj -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test10.txt: -------------------------------------------------------------------------------- 1 | fgsiku;liu[y89]5shjnt 03543sa -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test2.txt: -------------------------------------------------------------------------------- 1 | 13254543343dfa -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test3.txt: -------------------------------------------------------------------------------- 1 | rhh312d.g0g43erwh0s -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test4.txt: -------------------------------------------------------------------------------- 1 | ffssgryh6ffffffffff3ssssssss -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test5.txt: -------------------------------------------------------------------------------- 1 | fgsrkjdkflkn489oo0knra -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test6.txt: -------------------------------------------------------------------------------- 1 | dhrqr8661.z1g -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test7.txt: -------------------------------------------------------------------------------- 1 | dhrgzbnjtj461zdg31356j -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test8.txt: -------------------------------------------------------------------------------- 1 | dfajmdtx0654.z.41h 2 | -------------------------------------------------------------------------------- /app/src/main/assets/testdata/test9.txt: -------------------------------------------------------------------------------- 1 | fgsgjttikpsxmz034g6j -------------------------------------------------------------------------------- /app/src/main/assets/wordlist.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangshao45612/FileToDbDemo/7a4e5a7b7116a9026523d153132d5c59e74f778f/app/src/main/assets/wordlist.xls -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.view.View; 6 | 7 | import com.zsj.filetodbdemo.assetsfiles.AssetsFileAsynTask; 8 | import com.zsj.filetodbdemo.excel.extravoice.ExtraVoiceAsynTask; 9 | import com.zsj.filetodbdemo.assetsdb.GetWordInfoAsynTask; 10 | import com.zsj.filetodbdemo.excel.vocabulary.VocabularyDBHelper; 11 | import com.zsj.filetodbdemo.util.CopyDbFromAsset; 12 | 13 | public class MainActivity extends Activity implements View.OnClickListener { 14 | 15 | @Override 16 | protected void onCreate(Bundle savedInstanceState) { 17 | super.onCreate(savedInstanceState); 18 | setContentView(R.layout.activity_main); 19 | } 20 | 21 | @Override 22 | public void onClick(View view) { 23 | int vId = view.getId(); 24 | switch (vId) { 25 | case R.id.btn_excel_to_db_id: 26 | clickExcelToDb(); 27 | break; 28 | case R.id.btn_assets_db_to_db_id: 29 | clickAssetsDbToDb(); 30 | break; 31 | case R.id.btn_assets_files_to_db_id: 32 | clickAssetsFilesToDb(); 33 | break; 34 | case R.id.btn_get_assets_db_id: 35 | clickGetAssetsDb(); 36 | break; 37 | default: 38 | break; 39 | } 40 | } 41 | 42 | private void clickGetAssetsDb() { 43 | GetWordInfoAsynTask getWordInfoTask = new GetWordInfoAsynTask(this); 44 | getWordInfoTask.execute("2012版人教精通小学英语三年级上册(三年级起点)"); 45 | } 46 | 47 | private void clickAssetsFilesToDb() { 48 | AssetsFileAsynTask task = new AssetsFileAsynTask(this); 49 | task.execute(); 50 | } 51 | 52 | private void clickAssetsDbToDb() { 53 | //从assets里拷贝db文件到自己数据库 54 | CopyDbFromAsset.copyDbFromAssetToMySelf(getApplicationContext(), VocabularyDBHelper.DATA_BASE_NAME); 55 | } 56 | 57 | private void clickExcelToDb() { 58 | ExtraVoiceAsynTask extraTask = new ExtraVoiceAsynTask(this); 59 | extraTask.execute(); 60 | // VocabularyAsynTask vocabularyTask = new VocabularyAsynTask(this); 61 | // vocabularyTask.execute(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/assetsdb/GetWordInfoAsynTask.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.assetsdb; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import android.content.Context; 7 | import android.database.Cursor; 8 | import android.database.sqlite.SQLiteDatabase; 9 | import android.database.sqlite.SQLiteException; 10 | import android.os.AsyncTask; 11 | import android.text.TextUtils; 12 | import android.util.Log; 13 | 14 | import com.zsj.filetodbdemo.excel.vocabulary.VocabularyInfo; 15 | import com.zsj.filetodbdemo.util.AssetsDatabaseManager; 16 | import com.zsj.filetodbdemo.util.ListUtils; 17 | 18 | public class GetWordInfoAsynTask extends AsyncTask> { 19 | private static final String TAG = "GetWordInfoAsynTask"; 20 | private static final String EXCEPTION = "exception"; 21 | private Context mContext = null; 22 | private AssetsDatabaseManager dbManager = null; 23 | 24 | public GetWordInfoAsynTask(Context context) { 25 | this.mContext = context; 26 | // 初始化,只需要调用一次 27 | AssetsDatabaseManager.initManager(context); 28 | } 29 | 30 | @Override 31 | protected void onPostExecute(List vocabularyInfos) { 32 | super.onPostExecute(vocabularyInfos); 33 | if (ListUtils.isEmpty(vocabularyInfos)){ 34 | Log.d("zsj_getwordinfo","vocabularyInfos is null"); 35 | }else { 36 | Log.d("zsj_getwordinfo","vocabularyInfos :" + vocabularyInfos); 37 | } 38 | } 39 | 40 | @Override 41 | protected List doInBackground(String... params) { 42 | // 获取管理对象,因为数据库需要通过管理对象才能够获取 43 | dbManager = AssetsDatabaseManager.getManager(); 44 | // 通过管理对象获取数据库 45 | SQLiteDatabase db = dbManager.getDatabase("VocabularyInfoCfg.db"); 46 | List wordList = getWordInfo(db,params[0]); 47 | return wordList; 48 | } 49 | 50 | private List getWordInfo(SQLiteDatabase db, String bookNameStr) { 51 | List wordList = new ArrayList(); 52 | if (db == null || TextUtils.isEmpty(bookNameStr)) { 53 | return wordList; 54 | } 55 | 56 | VocabularyInfo info = null; 57 | Cursor cursor = null; 58 | try { 59 | cursor = db.rawQuery("select * from VocabularyInfo where bookname LIKE ?", new String[] { "%" + bookNameStr + "%" }); 60 | if (cursor != null && cursor.moveToFirst()) { 61 | do { 62 | String bookName = cursor.getString(cursor.getColumnIndex("bookname")); 63 | int startPage = cursor.getInt(cursor.getColumnIndex("startpage")); 64 | int endPage = cursor.getInt(cursor.getColumnIndex("endpage")); 65 | int curUnit = cursor.getInt(cursor.getColumnIndex("curunit")); 66 | String unitName = cursor.getString(cursor.getColumnIndex("unitname")); 67 | int wordNums = cursor.getInt(cursor.getColumnIndex("wordnums")); 68 | 69 | info = new VocabularyInfo(bookName, startPage, endPage, curUnit, unitName, wordNums); 70 | if (info != null) { 71 | wordList.add(info); 72 | } 73 | } while (cursor.moveToNext()); 74 | } 75 | 76 | } catch (SQLiteException e) { 77 | Log.e(TAG, EXCEPTION, e); 78 | } catch (Exception e) { 79 | Log.e(TAG, EXCEPTION, e); 80 | } finally { 81 | if (cursor != null) { 82 | cursor.close(); 83 | cursor = null; 84 | } 85 | if (db != null) { 86 | db.close(); 87 | } 88 | } 89 | 90 | return wordList; 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/assetsfiles/AssetsFileAsynTask.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.assetsfiles; 2 | 3 | import android.content.Context; 4 | import android.os.AsyncTask; 5 | import android.widget.Toast; 6 | 7 | public class AssetsFileAsynTask extends AsyncTask { 8 | 9 | private Context mContext = null; 10 | private AssetsFileDBManager dbManager = null; 11 | 12 | public AssetsFileAsynTask(Context context) { 13 | this.mContext = context; 14 | } 15 | 16 | @Override 17 | protected Void doInBackground(Void... params) { 18 | dbManager = AssetsFileDBManager.getInstance(mContext); 19 | return null; 20 | } 21 | 22 | @Override 23 | protected void onPostExecute(Void aVoid) { 24 | super.onPostExecute(aVoid); 25 | Toast.makeText(mContext.getApplicationContext(),"assets file保存到数据库完成",Toast.LENGTH_SHORT).show(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/assetsfiles/AssetsFileDBHelper.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.assetsfiles; 2 | 3 | import android.content.Context; 4 | import android.database.sqlite.SQLiteDatabase; 5 | import android.database.sqlite.SQLiteOpenHelper; 6 | 7 | public class AssetsFileDBHelper extends SQLiteOpenHelper { 8 | public static final String TABLE_ASSETS_FILE = "AssetsFile"; 9 | public static String DATA_BASE_NAME = "AssetsFileList.db"; 10 | private static final int VERSION = 1; 11 | private static AssetsFileDBHelper instance; 12 | 13 | public static AssetsFileDBHelper getInstance(Context context) { 14 | if (instance == null) { 15 | instance = new AssetsFileDBHelper(context); 16 | } 17 | return instance; 18 | } 19 | 20 | private AssetsFileDBHelper(Context context) { 21 | super(context, DATA_BASE_NAME, null, VERSION); 22 | } 23 | 24 | @Override 25 | public void onCreate(SQLiteDatabase db) { 26 | createTableAssetsFile(db); 27 | } 28 | 29 | @Override 30 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 31 | updateTableAssetsFile(db, oldVersion, newVersion); 32 | } 33 | 34 | /** 35 | * 创建用户表 36 | */ 37 | public void createTableAssetsFile(SQLiteDatabase db) { 38 | db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_ASSETS_FILE + " (_id INTEGER PRIMARY KEY AUTOINCREMENT" 39 | + ",fileName TEXT NOT NULL, " + "content BLOB )"); 40 | } 41 | 42 | /** 43 | * 更新用户表 44 | */ 45 | public void updateTableAssetsFile(SQLiteDatabase db, int oldVersion, int newVersion) { 46 | if (oldVersion != newVersion) { 47 | db.execSQL("DROP TABLE IF EXISTS " + TABLE_ASSETS_FILE); 48 | createTableAssetsFile(db); 49 | } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/assetsfiles/AssetsFileDBManager.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.assetsfiles; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | 8 | import android.content.ContentValues; 9 | import android.content.Context; 10 | import android.database.sqlite.SQLiteDatabase; 11 | import android.database.sqlite.SQLiteException; 12 | import android.util.Log; 13 | 14 | public class AssetsFileDBManager { 15 | private static final String TAG = "AssetsFileDBManager"; 16 | private static final String EXCEPTION = "exception"; 17 | private AssetsFileDBHelper mDBHelper = null; 18 | private static AssetsFileDBManager instance = null; 19 | 20 | public static AssetsFileDBManager getInstance(Context context) { 21 | if (instance == null) { 22 | instance = new AssetsFileDBManager(context.getApplicationContext()); 23 | } 24 | return instance; 25 | } 26 | 27 | private AssetsFileDBManager(Context context) { 28 | mDBHelper = AssetsFileDBHelper.getInstance(context); 29 | readAssetsFileToDB(context); 30 | } 31 | 32 | private void readAssetsFileToDB(Context context) { 33 | try { 34 | String assetFilePath = "testdata"; 35 | String[] h5Files = context.getAssets().list(assetFilePath); 36 | 37 | int sums = h5Files.length; 38 | AssetsFileInfo info = null; 39 | InputStream is = null; 40 | for (int i = 0; i < sums; ++i) { 41 | String fileName = h5Files[i]; 42 | 43 | is = context.getAssets().open(assetFilePath + File.separator + fileName); 44 | byte[] contents = input2byte(is); 45 | info = new AssetsFileInfo(fileName, contents); 46 | saveInfoToDataBase(info); 47 | Log.d("zsj", "cur position:" + i); 48 | } 49 | Log.d("zsj", "save over"); 50 | } catch (Exception e) { 51 | Log.e(TAG, EXCEPTION, e); 52 | } 53 | } 54 | 55 | private void saveInfoToDataBase(AssetsFileInfo info) { 56 | if (mDBHelper == null) { 57 | return; 58 | } 59 | SQLiteDatabase db = mDBHelper.getWritableDatabase(); 60 | try { 61 | ContentValues values = new ContentValues(); 62 | values.put("fileName", info.getFileName()); 63 | values.put("content", info.getFileBuffer()); 64 | db.insert(AssetsFileDBHelper.TABLE_ASSETS_FILE, null, values); 65 | } catch (SQLiteException e) { 66 | Log.e(TAG, EXCEPTION, e); 67 | } catch (Exception e) { 68 | Log.e(TAG, EXCEPTION, e); 69 | } finally { 70 | if (db != null) { 71 | db.close(); 72 | } 73 | } 74 | } 75 | 76 | private byte[] input2byte(InputStream inStream){ 77 | ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 78 | byte[] buff = new byte[100]; 79 | byte[] in2b = null; 80 | int rc = 0; 81 | try { 82 | while ((rc = inStream.read(buff, 0, 100)) > 0) { 83 | swapStream.write(buff, 0, rc); 84 | } 85 | in2b = swapStream.toByteArray(); 86 | } catch (IOException e) { 87 | // TODO Auto-generated catch block 88 | e.printStackTrace(); 89 | } 90 | return in2b; 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/assetsfiles/AssetsFileInfo.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.assetsfiles; 2 | 3 | public class AssetsFileInfo { 4 | // 索引 5 | private int id = 0; 6 | /** 7 | * 文件名称 8 | */ 9 | private String fileName = null; 10 | /** 11 | * 文件内容 12 | */ 13 | private byte[] fileBuffer = null; 14 | 15 | public int getId() { 16 | return id; 17 | } 18 | 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | 23 | public String getFileName() { 24 | return fileName; 25 | } 26 | 27 | public void setFileName(String fileName) { 28 | this.fileName = fileName; 29 | } 30 | 31 | public byte[] getFileBuffer() { 32 | return fileBuffer; 33 | } 34 | 35 | public void setFileBuffer(byte[] fileBuffer) { 36 | this.fileBuffer = fileBuffer; 37 | } 38 | 39 | public AssetsFileInfo(String fileName, byte[] fileBuffer) { 40 | super(); 41 | this.fileName = fileName; 42 | this.fileBuffer = fileBuffer; 43 | } 44 | 45 | public AssetsFileInfo() { 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/extravoice/ExtraVoiceAsynTask.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.extravoice; 2 | 3 | import android.content.Context; 4 | import android.os.AsyncTask; 5 | import android.widget.Toast; 6 | 7 | public class ExtraVoiceAsynTask extends AsyncTask { 8 | 9 | private Context mContext = null; 10 | private ExtraVoiceDBManager dbManager = null; 11 | 12 | public ExtraVoiceAsynTask(Context context) { 13 | this.mContext = context; 14 | } 15 | 16 | @Override 17 | protected Void doInBackground(Void... params) { 18 | dbManager = ExtraVoiceDBManager.getInstance(mContext); 19 | return null; 20 | } 21 | 22 | @Override 23 | protected void onPostExecute(Void aVoid) { 24 | super.onPostExecute(aVoid); 25 | Toast.makeText(mContext.getApplicationContext(),"excel保存到数据库完成",Toast.LENGTH_SHORT).show(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/extravoice/ExtraVoiceDBHelper.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.extravoice; 2 | 3 | import android.content.Context; 4 | import android.database.sqlite.SQLiteDatabase; 5 | import android.database.sqlite.SQLiteOpenHelper; 6 | 7 | /** 8 | * 配置数据库操作帮助类 9 | * 10 | * */ 11 | public class ExtraVoiceDBHelper extends SQLiteOpenHelper { 12 | 13 | public static final String TABLE_EXTRA_VOICE_INFO = "ExtraVoiceInfo"; 14 | public static String DATA_BASE_NAME = "ExtraVoiceCfg.db"; 15 | private static final int VERSION = 1; 16 | private static ExtraVoiceDBHelper instance; 17 | 18 | public static ExtraVoiceDBHelper getInstance( Context context ) { 19 | if (instance == null) { 20 | instance = new ExtraVoiceDBHelper( context ); 21 | } 22 | return instance; 23 | } 24 | 25 | public ExtraVoiceDBHelper(Context context){ 26 | super(context, DATA_BASE_NAME, null, VERSION); 27 | } 28 | 29 | @Override 30 | public void onCreate(SQLiteDatabase db) { 31 | createTableUser(db); 32 | } 33 | 34 | @Override 35 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 36 | updateTableUser(db, oldVersion, newVersion); 37 | } 38 | 39 | /** 40 | * 创建用户表 41 | * 42 | * */ 43 | public void createTableUser(SQLiteDatabase db){ 44 | db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_EXTRA_VOICE_INFO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT" 45 | + ",content TEXT NOT NULL, phonetic TEXT ,property TEXT, paraphrase TEXT ,usVoiceName TEXT NOT NULL, ukVoiceName TEXT NOT NULL)" ); 46 | } 47 | 48 | /** 49 | * 更新用户表 50 | * 51 | * */ 52 | public void updateTableUser(SQLiteDatabase db, int oldVersion, int newVersion){ 53 | if ( oldVersion != newVersion ){ 54 | db.execSQL( "DROP TABLE IF EXISTS " + TABLE_EXTRA_VOICE_INFO ); 55 | createTableUser(db); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/extravoice/ExtraVoiceDBManager.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.extravoice; 2 | 3 | import java.io.InputStream; 4 | 5 | import jxl.Sheet; 6 | import jxl.Workbook; 7 | 8 | import android.content.ContentValues; 9 | import android.content.Context; 10 | import android.database.Cursor; 11 | import android.database.sqlite.SQLiteDatabase; 12 | import android.database.sqlite.SQLiteException; 13 | import android.util.Log; 14 | 15 | import com.zsj.filetodbdemo.util.PreferencesUtils; 16 | 17 | public class ExtraVoiceDBManager { 18 | /** 19 | * 是否读取过补录语音数据 20 | */ 21 | public static final String IS_READED_EXTRA_SOUND_DATA = "is_readed_extra_sound_data"; 22 | 23 | private static final String TAG = "ExtraVoiceDBManager"; 24 | private static final String EXCEPTION = "exception"; 25 | private ExtraVoiceDBHelper mDBHelper = null; 26 | private static ExtraVoiceDBManager instance = null; 27 | 28 | public static ExtraVoiceDBManager getInstance(Context context) { 29 | if (instance == null) { 30 | instance = new ExtraVoiceDBManager(context.getApplicationContext()); 31 | } 32 | return instance; 33 | } 34 | 35 | private ExtraVoiceDBManager(Context context) { 36 | mDBHelper = ExtraVoiceDBHelper.getInstance(context); 37 | if (!PreferencesUtils.getBoolean(context, IS_READED_EXTRA_SOUND_DATA, false)) { 38 | readExcelToDB(context); 39 | } 40 | } 41 | 42 | private void readExcelToDB(Context context) { 43 | try { 44 | InputStream is = context.getAssets().open("extra_voice_data.xls"); 45 | Workbook book = Workbook.getWorkbook(is); 46 | book.getNumberOfSheets(); 47 | // 获得第一个工作表对象 48 | Sheet sheet = book.getSheet(0); 49 | int Rows = sheet.getRows(); 50 | ExtraVoiceInfo info = null; 51 | for (int i = 1; i < Rows; ++i) { 52 | String content = (sheet.getCell(0, i)).getContents(); 53 | String phonetic = (sheet.getCell(1, i)).getContents(); 54 | String property = (sheet.getCell(2, i)).getContents(); 55 | String paraphrase = (sheet.getCell(3, i)).getContents(); 56 | String usVoiceName = (sheet.getCell(4, i)).getContents(); 57 | String ukVoiceName = (sheet.getCell(5, i)).getContents(); 58 | 59 | info = new ExtraVoiceInfo(content, phonetic, property, paraphrase, usVoiceName, ukVoiceName); 60 | saveInfoToDataBase(info); 61 | } 62 | book.close(); 63 | Log.d("zsj_excel","excel读取完成"); 64 | PreferencesUtils.putBoolean(context, IS_READED_EXTRA_SOUND_DATA, true); 65 | } catch (Exception e) { 66 | Log.e(TAG, EXCEPTION, e); 67 | PreferencesUtils.putBoolean(context, IS_READED_EXTRA_SOUND_DATA, false); 68 | } 69 | } 70 | 71 | private void saveInfoToDataBase(ExtraVoiceInfo info) { 72 | if (mDBHelper == null) { 73 | return; 74 | } 75 | SQLiteDatabase db = mDBHelper.getWritableDatabase(); 76 | try { 77 | ContentValues values = new ContentValues(); 78 | values.put("content", info.getContent()); 79 | values.put("phonetic", info.getPhonetic()); 80 | values.put("property", info.getProperty()); 81 | values.put("paraphrase", info.getParaphrase()); 82 | values.put("usVoiceName", info.getUsVoiceName()); 83 | values.put("ukVoiceName", info.getUkVoiceName()); 84 | db.insert(ExtraVoiceDBHelper.TABLE_EXTRA_VOICE_INFO, null, values); 85 | } catch (SQLiteException e) { 86 | Log.e(TAG, EXCEPTION, e); 87 | } catch (Exception e){ 88 | Log.e(TAG, EXCEPTION, e); 89 | } finally { 90 | if (db != null) { 91 | db.close(); 92 | } 93 | } 94 | } 95 | 96 | public ExtraVoiceInfo getExtraVoiceInfo(String contentStr) { 97 | ExtraVoiceInfo info = null; 98 | if (mDBHelper == null) { 99 | return info; 100 | } 101 | 102 | SQLiteDatabase db = mDBHelper.getReadableDatabase(); 103 | 104 | if (db == null) { 105 | return info; 106 | } 107 | 108 | Cursor cursor = db.rawQuery("select * from ExtraVoiceInfo where content = ?", new String[] { contentStr }); 109 | 110 | try { 111 | if (cursor != null && cursor.moveToFirst()) { 112 | do { 113 | String content = cursor.getString(cursor.getColumnIndex("content")); 114 | String phonetic = cursor.getString(cursor.getColumnIndex("phonetic")); 115 | String property = cursor.getString(cursor.getColumnIndex("property")); 116 | String paraphrase = cursor.getString(cursor.getColumnIndex("paraphrase")); 117 | String usVoiceName = cursor.getString(cursor.getColumnIndex("usVoiceName")); 118 | String ukVoiceName = cursor.getString(cursor.getColumnIndex("ukVoiceName")); 119 | 120 | info = new ExtraVoiceInfo(content, phonetic, property, paraphrase, usVoiceName, ukVoiceName); 121 | } while (cursor.moveToNext()); 122 | } 123 | 124 | } catch (SQLiteException e) { 125 | Log.e(TAG, EXCEPTION, e); 126 | } catch (Exception e){ 127 | Log.e(TAG, EXCEPTION, e); 128 | } finally { 129 | if (cursor != null) { 130 | cursor.close(); 131 | cursor = null; 132 | } 133 | if (db != null) { 134 | db.close(); 135 | } 136 | } 137 | return info; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/extravoice/ExtraVoiceInfo.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.extravoice; 2 | 3 | public class ExtraVoiceInfo { 4 | private int id; 5 | /** 6 | * 单词内容 7 | */ 8 | private String content; 9 | /** 10 | * 音标 11 | */ 12 | private String phonetic; 13 | /** 14 | * 词性 15 | */ 16 | private String property; 17 | /** 18 | * 释义 19 | */ 20 | private String paraphrase; 21 | /** 22 | * 美式发音名称 23 | */ 24 | private String usVoiceName; 25 | /** 26 | * 英式发音名称 27 | */ 28 | private String ukVoiceName; 29 | 30 | public ExtraVoiceInfo() { 31 | } 32 | 33 | public ExtraVoiceInfo(int id, String content, String phonetic, String property, String paraphrase, 34 | String usVoiceName, String ukVoiceName) { 35 | super(); 36 | this.id = id; 37 | this.content = content; 38 | this.phonetic = phonetic; 39 | this.property = property; 40 | this.paraphrase = paraphrase; 41 | this.usVoiceName = usVoiceName; 42 | this.ukVoiceName = ukVoiceName; 43 | } 44 | 45 | public ExtraVoiceInfo(String content, String phonetic, String property, String paraphrase, String usVoiceName, 46 | String ukVoiceName) { 47 | super(); 48 | this.content = content; 49 | this.phonetic = phonetic; 50 | this.property = property; 51 | this.paraphrase = paraphrase; 52 | this.usVoiceName = usVoiceName; 53 | this.ukVoiceName = ukVoiceName; 54 | } 55 | 56 | public int getId() { 57 | return id; 58 | } 59 | 60 | public void setId(int id) { 61 | this.id = id; 62 | } 63 | 64 | public String getContent() { 65 | return content; 66 | } 67 | 68 | public void setContent(String content) { 69 | this.content = content; 70 | } 71 | 72 | public String getPhonetic() { 73 | return phonetic; 74 | } 75 | 76 | public void setPhonetic(String phonetic) { 77 | this.phonetic = phonetic; 78 | } 79 | 80 | public String getProperty() { 81 | return property; 82 | } 83 | 84 | public void setProperty(String property) { 85 | this.property = property; 86 | } 87 | 88 | public String getParaphrase() { 89 | return paraphrase; 90 | } 91 | 92 | public void setParaphrase(String paraphrase) { 93 | this.paraphrase = paraphrase; 94 | } 95 | 96 | public String getUsVoiceName() { 97 | return usVoiceName; 98 | } 99 | 100 | public void setUsVoiceName(String usVoiceName) { 101 | this.usVoiceName = usVoiceName; 102 | } 103 | 104 | public String getUkVoiceName() { 105 | return ukVoiceName; 106 | } 107 | 108 | public void setUkVoiceName(String ukVoiceName) { 109 | this.ukVoiceName = ukVoiceName; 110 | } 111 | 112 | @Override 113 | public String toString() { 114 | return "content:" + content + " phonetic:" + phonetic + " property:" + property + " paraphrase:" 115 | + paraphrase + " usVoiceName:" + usVoiceName + " ukVoiceName:" + ukVoiceName; 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/vocabulary/VocabularyAsynTask.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.vocabulary; 2 | 3 | import android.content.Context; 4 | import android.os.AsyncTask; 5 | import android.widget.Toast; 6 | 7 | public class VocabularyAsynTask extends AsyncTask { 8 | 9 | private Context mContext = null; 10 | private VocabularyDBManager dbManager = null; 11 | 12 | public VocabularyAsynTask(Context context) { 13 | this.mContext = context; 14 | } 15 | 16 | @Override 17 | protected Void doInBackground(Void... params) { 18 | dbManager = VocabularyDBManager.getInstance(mContext); 19 | return null; 20 | } 21 | 22 | @Override 23 | protected void onPostExecute(Void aVoid) { 24 | super.onPostExecute(aVoid); 25 | Toast.makeText(mContext.getApplicationContext(), "excel保存到数据库完成", Toast.LENGTH_SHORT).show(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/vocabulary/VocabularyDBHelper.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.vocabulary; 2 | 3 | import android.content.Context; 4 | import android.database.sqlite.SQLiteDatabase; 5 | import android.database.sqlite.SQLiteOpenHelper; 6 | 7 | /** 8 | * 配置数据库操作帮助类 9 | * 10 | * */ 11 | public class VocabularyDBHelper extends SQLiteOpenHelper { 12 | 13 | public static final String TABLE_VOCABULARY_INFO = "VocabularyInfo"; 14 | public static String DATA_BASE_NAME = "VocabularyInfoCfg.db"; 15 | private static final int VERSION = 1; 16 | private static VocabularyDBHelper instance; 17 | 18 | public static VocabularyDBHelper getInstance( Context context ) { 19 | if (instance == null) { 20 | instance = new VocabularyDBHelper( context ); 21 | } 22 | return instance; 23 | } 24 | 25 | public VocabularyDBHelper(Context context){ 26 | super(context, DATA_BASE_NAME, null, VERSION); 27 | } 28 | 29 | @Override 30 | public void onCreate(SQLiteDatabase db) { 31 | createTableUser(db); 32 | } 33 | 34 | @Override 35 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 36 | updateTableUser(db, oldVersion, newVersion); 37 | } 38 | 39 | /** 40 | * 创建用户表 41 | * 42 | * */ 43 | public void createTableUser(SQLiteDatabase db){ 44 | db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_VOCABULARY_INFO + " (_id INTEGER PRIMARY KEY AUTOINCREMENT" 45 | + ",bookname TEXT NOT NULL, " + 46 | "startpage INTEGER ," + 47 | "endpage INTEGER, " + 48 | "curunit INTEGER ," + 49 | "unitname TEXT NOT NULL, " + 50 | "wordnums INTEGER)" ); 51 | } 52 | 53 | /** 54 | * 更新用户表 55 | * 56 | * */ 57 | public void updateTableUser(SQLiteDatabase db, int oldVersion, int newVersion){ 58 | if ( oldVersion != newVersion ){ 59 | db.execSQL( "DROP TABLE IF EXISTS " + TABLE_VOCABULARY_INFO ); 60 | createTableUser(db); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/vocabulary/VocabularyDBManager.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.vocabulary; 2 | 3 | import java.io.InputStream; 4 | 5 | import jxl.Sheet; 6 | import jxl.Workbook; 7 | 8 | import android.content.ContentValues; 9 | import android.content.Context; 10 | import android.database.sqlite.SQLiteDatabase; 11 | import android.database.sqlite.SQLiteException; 12 | import android.util.Log; 13 | 14 | import com.zsj.filetodbdemo.util.PreferencesUtils; 15 | 16 | public class VocabularyDBManager { 17 | public static final String IS_READED_EXTRA_VOCABULARY_DATA = "is_readed_extra_vocabulary_data"; 18 | 19 | private static final String TAG = "VocabularyDBManager"; 20 | private static final String EXCEPTION = "exception"; 21 | private VocabularyDBHelper mDBHelper = null; 22 | private static VocabularyDBManager instance = null; 23 | 24 | public static VocabularyDBManager getInstance(Context context) { 25 | if (instance == null) { 26 | instance = new VocabularyDBManager(context.getApplicationContext()); 27 | } 28 | return instance; 29 | } 30 | 31 | private VocabularyDBManager(Context context) { 32 | mDBHelper = VocabularyDBHelper.getInstance(context); 33 | if (!PreferencesUtils.getBoolean(context, IS_READED_EXTRA_VOCABULARY_DATA, false)) { 34 | readExcelToDB(context); 35 | } 36 | } 37 | 38 | private void readExcelToDB(Context context) { 39 | try { 40 | InputStream is = context.getAssets().open("wordlist.xls"); 41 | Workbook book = Workbook.getWorkbook(is); 42 | book.getNumberOfSheets(); 43 | // 获得第一个工作表对象 44 | Sheet sheet = book.getSheet(0); 45 | int Rows = sheet.getRows(); 46 | VocabularyInfo info = null; 47 | for (int i = 1; i < Rows; ++i) { 48 | String bookName = (sheet.getCell(0, i)).getContents(); 49 | String startPage = (sheet.getCell(1, i)).getContents(); 50 | String endPage = (sheet.getCell(2, i)).getContents(); 51 | String curUnit = (sheet.getCell(3, i)).getContents(); 52 | String unitName = (sheet.getCell(4, i)).getContents(); 53 | String wordNums = (sheet.getCell(5, i)).getContents(); 54 | 55 | info = new VocabularyInfo(bookName, Integer.parseInt(startPage), Integer.parseInt(endPage), 56 | Integer.parseInt(curUnit), unitName, Integer.parseInt(wordNums)); 57 | saveInfoToDataBase(info); 58 | Log.d("zsj", "cur position:" + i); 59 | } 60 | Log.d("zsj", "save over"); 61 | book.close(); 62 | PreferencesUtils.putBoolean(context, IS_READED_EXTRA_VOCABULARY_DATA, true); 63 | } catch (Exception e) { 64 | PreferencesUtils.putBoolean(context, IS_READED_EXTRA_VOCABULARY_DATA, false); 65 | Log.e(TAG, EXCEPTION, e); 66 | } 67 | } 68 | 69 | private void saveInfoToDataBase(VocabularyInfo info) { 70 | if (mDBHelper == null) { 71 | return; 72 | } 73 | SQLiteDatabase db = mDBHelper.getWritableDatabase(); 74 | try { 75 | ContentValues values = new ContentValues(); 76 | values.put("bookname", info.getBookName()); 77 | values.put("startpage", info.getStartPage()); 78 | values.put("endpage", info.getEndPage()); 79 | values.put("curunit", info.getCurUnit()); 80 | values.put("unitname", info.getCurUnitName()); 81 | values.put("wordnums", info.getWordNums()); 82 | db.insert(VocabularyDBHelper.TABLE_VOCABULARY_INFO, null, values); 83 | } catch (SQLiteException e) { 84 | Log.e(TAG, EXCEPTION, e); 85 | } catch (Exception e){ 86 | Log.e(TAG, EXCEPTION, e); 87 | } finally { 88 | if (db != null) { 89 | db.close(); 90 | } 91 | } 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/excel/vocabulary/VocabularyInfo.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.excel.vocabulary; 2 | 3 | public class VocabularyInfo { 4 | private int id; 5 | /** 教材名称 **/ 6 | private String bookName; 7 | /** 起始页 **/ 8 | private int startPage; 9 | /** 结束页 **/ 10 | private int endPage; 11 | /** 当前第几单元 **/ 12 | private int curUnit; 13 | /** 单元名称 **/ 14 | private String curUnitName; 15 | /** 每个单元有几个单词(包含单元名称) **/ 16 | private int wordNums; 17 | 18 | public VocabularyInfo(int id, String bookName, int startPage, int endPage, int curUnit, String curUnitName, int wordNums) { 19 | super(); 20 | this.id = id; 21 | this.bookName = bookName; 22 | this.startPage = startPage; 23 | this.endPage = endPage; 24 | this.curUnit = curUnit; 25 | this.curUnitName = curUnitName; 26 | this.wordNums = wordNums; 27 | } 28 | 29 | public VocabularyInfo(String bookName, int startPage, int endPage, int curUnit, String curUnitName, int wordNums) { 30 | super(); 31 | this.bookName = bookName; 32 | this.startPage = startPage; 33 | this.endPage = endPage; 34 | this.curUnit = curUnit; 35 | this.curUnitName = curUnitName; 36 | this.wordNums = wordNums; 37 | } 38 | 39 | 40 | public VocabularyInfo() { 41 | } 42 | 43 | public int getId() { 44 | return id; 45 | } 46 | 47 | public void setId(int id) { 48 | this.id = id; 49 | } 50 | 51 | public String getBookName() { 52 | return bookName; 53 | } 54 | 55 | public void setBookName(String bookName) { 56 | this.bookName = bookName; 57 | } 58 | 59 | public int getStartPage() { 60 | return startPage; 61 | } 62 | 63 | public void setStartPage(int startPage) { 64 | this.startPage = startPage; 65 | } 66 | 67 | public int getEndPage() { 68 | return endPage; 69 | } 70 | 71 | public void setEndPage(int endPage) { 72 | this.endPage = endPage; 73 | } 74 | 75 | public int getCurUnit() { 76 | return curUnit; 77 | } 78 | 79 | public void setCurUnit(int curUnit) { 80 | this.curUnit = curUnit; 81 | } 82 | 83 | public String getCurUnitName() { 84 | return curUnitName; 85 | } 86 | 87 | public void setCurUnitName(String curUnitName) { 88 | this.curUnitName = curUnitName; 89 | } 90 | 91 | public int getWordNums() { 92 | return wordNums; 93 | } 94 | 95 | public void setWordNums(int wordNums) { 96 | this.wordNums = wordNums; 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/util/AssetsDatabaseManager.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.util; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.InputStream; 6 | import java.io.OutputStream; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | import android.annotation.SuppressLint; 11 | import android.content.Context; 12 | import android.content.SharedPreferences; 13 | import android.content.res.AssetManager; 14 | import android.database.sqlite.SQLiteDatabase; 15 | import android.util.Log; 16 | 17 | /** 18 | * This is a Assets Database Manager 19 | * Use it, you can use a assets database file in you application 20 | * It will copy the database file to "/data/data/[your application package name]/database" when you first time you use it 21 | * Then you can get a SQLiteDatabase object by the assets database file 22 | * @author RobinTang 23 | * @time 2012-09-20 24 | * 25 | * 26 | * How to use: 27 | * 1. Initialize AssetsDatabaseManager 28 | * 2. Get AssetsDatabaseManager 29 | * 3. Get a SQLiteDatabase object through database file 30 | * 4. Use this database object 31 | * 32 | * Using example: 33 | * AssetsDatabaseManager.initManager(getApplication()); // this method is only need call one time 34 | * AssetsDatabaseManager mg = AssetsDatabaseManager.getManager(); // get a AssetsDatabaseManager object 35 | * SQLiteDatabase db1 = mg.getDatabase("db1.db"); // get SQLiteDatabase object, db1.db is a file in assets folder 36 | * db1.??? // every operate by you want 37 | * Of cause, you can use AssetsDatabaseManager.getManager().getDatabase("xx") to get a database when you need use a database 38 | */ 39 | public class AssetsDatabaseManager { 40 | private static String tag = "AssetsDatabase"; // for LogCat 41 | @SuppressLint("SdCardPath") 42 | private static String databasepath = "/data/data/%s/databases"; // %s is packageName 43 | 44 | 45 | // A mapping from assets database file to SQLiteDatabase object 46 | private Map databases = new HashMap(); 47 | 48 | // Context of application 49 | private Context context = null; 50 | 51 | // Singleton Pattern 52 | private static AssetsDatabaseManager mInstance = null; 53 | 54 | /** 55 | * Initialize AssetsDatabaseManager 56 | * @param context, context of application 57 | */ 58 | public static void initManager(Context context){ 59 | if(mInstance == null){ 60 | mInstance = new AssetsDatabaseManager(context); 61 | } 62 | } 63 | 64 | /** 65 | * Get a AssetsDatabaseManager object 66 | * @return, if success return a AssetsDatabaseManager object, else return null 67 | */ 68 | public static AssetsDatabaseManager getManager(){ 69 | return mInstance; 70 | } 71 | 72 | private AssetsDatabaseManager(Context context){ 73 | this.context = context; 74 | } 75 | 76 | /** 77 | * Get a assets database, if this database is opened this method is only return a copy of the opened database 78 | * @param dbfile, the assets file which will be opened for a database 79 | * @return, if success it return a SQLiteDatabase object else return null 80 | */ 81 | public SQLiteDatabase getDatabase(String dbfile) { 82 | if(databases.get(dbfile) != null){ 83 | Log.i(tag, String.format("Return a database copy of %s", dbfile)); 84 | return (SQLiteDatabase) databases.get(dbfile); 85 | } 86 | if(context==null) 87 | return null; 88 | 89 | Log.i(tag, String.format("Create database %s", dbfile)); 90 | String spath = getDatabaseFilepath(); 91 | String sfile = getDatabaseFile(dbfile); 92 | 93 | File file = new File(sfile); 94 | SharedPreferences dbs = context.getSharedPreferences(AssetsDatabaseManager.class.toString(), 0); 95 | boolean flag = dbs.getBoolean(dbfile, false); // Get Database file flag, if true means this database file was copied and valid 96 | if(!flag || !file.exists()){ 97 | file = new File(spath); 98 | if(!file.exists() && !file.mkdirs()){ 99 | Log.i(tag, "Create \""+spath+"\" fail!"); 100 | return null; 101 | } 102 | if(!copyAssetsToFilesystem(dbfile, sfile)){ 103 | Log.i(tag, String.format("Copy %s to %s fail!", dbfile, sfile)); 104 | return null; 105 | } 106 | 107 | dbs.edit().putBoolean(dbfile, true).commit(); 108 | } 109 | 110 | SQLiteDatabase db = SQLiteDatabase.openDatabase(sfile, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 111 | if(db != null){ 112 | databases.put(dbfile, db); 113 | } 114 | return db; 115 | } 116 | 117 | private String getDatabaseFilepath(){ 118 | return String.format(databasepath, context.getApplicationInfo().packageName); 119 | } 120 | 121 | private String getDatabaseFile(String dbfile){ 122 | return getDatabaseFilepath()+"/"+dbfile; 123 | } 124 | 125 | private boolean copyAssetsToFilesystem(String assetsSrc, String des){ 126 | Log.i(tag, "Copy "+assetsSrc+" to "+des); 127 | InputStream istream = null; 128 | OutputStream ostream = null; 129 | try{ 130 | AssetManager am = context.getAssets(); 131 | istream = am.open(assetsSrc); 132 | ostream = new FileOutputStream(des); 133 | byte[] buffer = new byte[1024]; 134 | int length; 135 | while ((length = istream.read(buffer))>0){ 136 | ostream.write(buffer, 0, length); 137 | } 138 | istream.close(); 139 | ostream.close(); 140 | } 141 | catch(Exception e){ 142 | e.printStackTrace(); 143 | try{ 144 | if(istream!=null) 145 | istream.close(); 146 | if(ostream!=null) 147 | ostream.close(); 148 | } 149 | catch(Exception ee){ 150 | ee.printStackTrace(); 151 | } 152 | return false; 153 | } 154 | return true; 155 | } 156 | 157 | /** 158 | * Close assets database 159 | * @param dbfile, the assets file which will be closed soon 160 | * @return, the status of this operating 161 | */ 162 | public boolean closeDatabase(String dbfile){ 163 | if(databases.get(dbfile) != null){ 164 | SQLiteDatabase db = (SQLiteDatabase) databases.get(dbfile); 165 | db.close(); 166 | databases.remove(dbfile); 167 | return true; 168 | } 169 | return false; 170 | } 171 | 172 | /** 173 | * Close all assets database 174 | */ 175 | public static void closeAllDatabase(){ 176 | Log.i(tag, "closeAllDatabase"); 177 | if(mInstance != null){ 178 | for(int i=0; i0){ 56 | ostream.write(buffer, 0, length); 57 | } 58 | istream.close(); 59 | ostream.close(); 60 | } 61 | catch(Exception e){ 62 | e.printStackTrace(); 63 | try{ 64 | if(istream!=null) 65 | istream.close(); 66 | if(ostream!=null) 67 | ostream.close(); 68 | } 69 | catch(Exception ee){ 70 | ee.printStackTrace(); 71 | } 72 | return false; 73 | } 74 | return true; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/util/ListUtils.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.util; 2 | 3 | import android.text.TextUtils; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Random; 8 | 9 | /** 10 | *
    11 | *
  • {@link ListUtils#getSize(List)}
  • 12 | *
  • {@link ListUtils#isEmpty(List)}
  • 13 | *
  • {@link ListUtils#isEquals(List, List)}
  • 14 | *
  • {@link ListUtils#isEquals(Object, Object)}
  • 15 | *
  • {@link ListUtils#join(List)}
  • 16 | *
  • {@link ListUtils#join(List,char)}
  • 17 | *
  • {@link ListUtils#addDistinctEntry(List, Object)}
  • 18 | *
  • {@link ListUtils#addDistinctList(List, List)}
  • 19 | *
  • {@link ListUtils#addListNotNullValue(List, Object)}
  • 20 | *
  • {@link ListUtils#invertList(List)}
  • 21 | *
  • {@link ListUtils#randomList(List)}
  • 22 | *
23 | * 24 | */ 25 | public class ListUtils { 26 | public static final String DEFAULT_JOIN_SEPARATOR = ","; 27 | private ListUtils( ){ 28 | throw new AssertionError( ); 29 | } 30 | 31 | /** 32 | * get size of list 33 | * 34 | *
 35 |      * getSize(null)   =   0;
 36 |      * getSize({})     =   0;
 37 |      * getSize({1})    =   1;
 38 |      * 
39 | * 40 | * @param 41 | * @param sourceList 42 | * @return if list is null or empty, return 0, else return {@link List#size()}. 43 | */ 44 | public static int getSize(List sourceList) { 45 | if( isEmpty( sourceList ) ){ 46 | throw new IllegalArgumentException( "sourceList is illegal, please check it!" ); 47 | } 48 | 49 | return sourceList == null ? 0 : sourceList.size(); 50 | } 51 | 52 | /** 53 | * is null or its size is 0 54 | * 55 | *
 56 |      * isEmpty(null)   =   true;
 57 |      * isEmpty({})     =   true;
 58 |      * isEmpty({1})    =   false;
 59 |      * 
60 | * 61 | * @param 62 | * @param sourceList 63 | * @return if list is null or its size is 0, return true, else return false. 64 | */ 65 | public static boolean isEmpty(List sourceList) { 66 | return (sourceList == null || sourceList.size() == 0); 67 | } 68 | 69 | /** 70 | * compare two list 71 | * 72 | *
 73 |      * isEquals(null, null) = true;
 74 |      * isEquals(new List<String>(), null) = false;
 75 |      * isEquals(null, new List<String>()) = false;
 76 |      * isEquals(new List<String>(), new List<String>()) = true;
 77 |      * 
78 | * 79 | * @param 80 | * @param actual 81 | * @param expected 82 | * @return true equal,false nonequal 83 | */ 84 | public static boolean isEquals(List actual, List expected) { 85 | if( isEmpty( actual ) || isEmpty( expected )){ 86 | throw new IllegalArgumentException( "actual or expected is illegal, please check it!" ); 87 | } 88 | 89 | if (actual.size() != expected.size()) { 90 | return false; 91 | } 92 | 93 | for (int i = 0; i < actual.size(); i++) { 94 | System.out.println( "actual == " + actual.get(i) + " expected == " + expected.get(i) ); 95 | if (!isEquals(actual.get(i), expected.get(i))) { 96 | return false; 97 | } 98 | } 99 | return true; 100 | } 101 | 102 | /** 103 | * compare two object 104 | * 105 | * @param actual 106 | * @param expected 107 | * @return
    108 | *
  • if both are null, return true
  • 109 | *
  • return actual.{@link Object#equals(Object)}
  • 110 | *
111 | */ 112 | private static boolean isEquals(Object actual, Object expected) { 113 | if( null == actual || null == expected ){ 114 | throw new IllegalArgumentException( "actual or expected is illegal, please check it!" ); 115 | } 116 | 117 | return actual == expected || (actual == null ? expected == null : actual.equals(expected)); 118 | } 119 | 120 | /** 121 | * join list to string, separator is "," 122 | * 123 | *
124 |      * join(null)      =   "";
125 |      * join({})        =   "";
126 |      * join({a,b})     =   "a,b";
127 |      * 
128 | * 129 | * @param list 130 | * @return join list to string, separator is ",". if list is empty, return "" 131 | */ 132 | public static String join(List list) { 133 | if( isEmpty( list ) ){ 134 | throw new IllegalArgumentException( "list is illegal, please check it!" ); 135 | } 136 | 137 | return join(list, DEFAULT_JOIN_SEPARATOR); 138 | } 139 | 140 | /** 141 | * join list to string 142 | * 143 | *
144 |      * join(null, '#')     =   "";
145 |      * join({}, '#')       =   "";
146 |      * join({a,b,c}, ' ')  =   "abc";
147 |      * join({a,b,c}, '#')  =   "a#b#c";
148 |      * 
149 | * 150 | * @param list 151 | * @param separator 152 | * @return join list to string. if list is empty, return "" 153 | */ 154 | public static String join(List list, char separator) { 155 | if( isEmpty( list ) ){ 156 | throw new IllegalArgumentException( "list is illegal, please check it!" ); 157 | } 158 | 159 | return join(list, new String(new char[] {separator})); 160 | } 161 | 162 | /** 163 | * join list to string. if separator is null, use {@link #DEFAULT_JOIN_SEPARATOR} 164 | * 165 | *
166 |      * join(null, "#")     =   "";
167 |      * join({}, "#$")      =   "";
168 |      * join({a,b,c}, null) =   "a,b,c";
169 |      * join({a,b,c}, "")   =   "abc";
170 |      * join({a,b,c}, "#")  =   "a#b#c";
171 |      * join({a,b,c}, "#$") =   "a#$b#$c";
172 |      * 
173 | * 174 | * @param list 175 | * @param separator 176 | * @return join list to string with separator. if list is empty, return "" 177 | */ 178 | public static String join(List list, String separator) { 179 | if( isEmpty( list ) || TextUtils.isEmpty( separator ) ){ 180 | throw new IllegalArgumentException( "list or separator is illegal, please check it!" ); 181 | } 182 | 183 | if (separator == null) { 184 | separator = DEFAULT_JOIN_SEPARATOR; 185 | } 186 | 187 | StringBuilder joinStr = new StringBuilder(); 188 | for (int i = 0; i < list.size(); i++) { 189 | joinStr.append(list.get(i)); 190 | if (i != list.size() - 1) { 191 | joinStr.append(separator); 192 | } 193 | } 194 | return joinStr.toString(); 195 | } 196 | 197 | /** 198 | * add distinct entry to list 199 | * 200 | * @param 201 | * @param sourceList 202 | * @param entry 203 | * @return if entry already exist in sourceList, return false, else add it and return true. 204 | */ 205 | public static boolean addDistinctEntry(List sourceList, V entry) { 206 | if( isEmpty( sourceList ) || null == entry ){ 207 | throw new IllegalArgumentException( "sourceList or entry is illegal, please check it!" ); 208 | } 209 | 210 | return (sourceList != null && !sourceList.contains(entry)) ? sourceList.add(entry) : false; 211 | } 212 | 213 | /** 214 | * add all distinct entry to list1 from list2 215 | * 216 | * @param 217 | * @param sourceList 218 | * @param entryList 219 | * @return the count of entries be added 220 | */ 221 | public static int addDistinctList(List sourceList, List entryList) { 222 | if( isEmpty( sourceList ) || isEmpty( entryList ) ){ 223 | throw new IllegalArgumentException( "sourceList or entryList is illegal, please check it!" ); 224 | } 225 | 226 | int sourceCount = sourceList.size(); 227 | for (V entry : entryList) { 228 | if (!sourceList.contains(entry)) { 229 | sourceList.add(entry); 230 | } 231 | } 232 | return sourceList.size() - sourceCount; 233 | } 234 | 235 | /** 236 | * add not null entry to list 237 | * 238 | * @param sourceList 239 | * @param value 240 | * @return
    241 | *
  • if sourceList is null, return false
  • 242 | *
  • if value is null, return false
  • 243 | *
  • return {@link List#add(Object)}
  • 244 | *
245 | */ 246 | public static boolean addListNotNullValue(List sourceList, V value) { 247 | if( isEmpty( sourceList ) || null == value ){ 248 | throw new IllegalArgumentException( "sourceList or value is illegal, please check it!" ); 249 | } 250 | 251 | return (sourceList != null && value != null) ? sourceList.add(value) : false; 252 | } 253 | 254 | /** 255 | * invert list 256 | * 257 | * @param sourceList 258 | * @return random list 259 | */ 260 | public static List invertList(List sourceList) { 261 | if (isEmpty(sourceList)) { 262 | throw new IllegalArgumentException( "sourceList is illegal, please check it!" ); 263 | } 264 | 265 | List invertList = new ArrayList(sourceList.size()); 266 | for (int i = sourceList.size() - 1; i >= 0; i--) { 267 | invertList.add(sourceList.get(i)); 268 | } 269 | 270 | return invertList; 271 | } 272 | 273 | /** 274 | * 打乱List 275 | * 276 | * */ 277 | public static List randomList(List sourceList){ 278 | // Collections.shuffle( sourceList ); 可以用这个方法代替 279 | if (ListUtils.isEmpty( sourceList )) { 280 | throw new IllegalArgumentException( "sourceList is illegal, please check it!" ); 281 | } 282 | 283 | List randomList = new ArrayList( sourceList.size( ) ); 284 | do{ 285 | int randomIndex = Math.abs( new Random( ).nextInt( sourceList.size() ) ); 286 | randomList.add( sourceList.remove( randomIndex ) ); 287 | }while( !ListUtils.isEmpty( sourceList ) ); 288 | 289 | return randomList; 290 | } 291 | } 292 | -------------------------------------------------------------------------------- /app/src/main/java/com/zsj/filetodbdemo/util/PreferencesUtils.java: -------------------------------------------------------------------------------- 1 | package com.zsj.filetodbdemo.util; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | /** 7 | * PreferencesUtils, easy to get or put data 8 | *
    9 | * Preference Name 10 | *
  • you can change preference name by {@link #PREFERENCE_NAME}
  • 11 | *
12 | *
    13 | * Put Value 14 | *
  • put string {@link #putString(Context, String, String)}
  • 15 | *
  • put int {@link #putInt(Context, String, int)}
  • 16 | *
  • put long {@link #putLong(Context, String, long)}
  • 17 | *
  • put float {@link #putFloat(Context, String, float)}
  • 18 | *
  • put boolean {@link #putBoolean(Context, String, boolean)}
  • 19 | *
20 | *
    21 | * Get Value 22 | *
  • get string {@link #getString(Context, String)}, {@link #getString(Context, String, String)}
  • 23 | *
  • get int {@link #getInt(Context, String)}, {@link #getInt(Context, String, int)}
  • 24 | *
  • get long {@link #getLong(Context, String)}, {@link #getLong(Context, String, long)}
  • 25 | *
  • get float {@link #getFloat(Context, String)}, {@link #getFloat(Context, String, float)}
  • 26 | *
  • get boolean {@link #getBoolean(Context, String)}, {@link #getBoolean(Context, String, boolean)}
  • 27 | *
28 | * 29 | */ 30 | public class PreferencesUtils { 31 | public static String PREFERENCE_NAME = "Open"; 32 | private PreferencesUtils() { 33 | throw new AssertionError(); 34 | } 35 | 36 | /** 37 | * put string preferences 38 | * 39 | * @param context 40 | * @param key The name of the preference to modify 41 | * @param value The new value for the preference 42 | * @return True if the new values were successfully written to persistent storage. 43 | */ 44 | public static boolean putString(Context context, String key, String value) { 45 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 46 | SharedPreferences.Editor editor = settings.edit(); 47 | editor.putString(key, value); 48 | return editor.commit(); 49 | } 50 | 51 | /** 52 | * get string preferences 53 | * 54 | * @param context 55 | * @param key The name of the preference to retrieve 56 | * @return The preference value if it exists, or null. Throws ClassCastException if there is a preference with this 57 | * name that is not a string 58 | * @see #getString(Context, String, String) 59 | */ 60 | public static String getString(Context context, String key) { 61 | return getString(context, key, null); 62 | } 63 | 64 | /** 65 | * get string preferences 66 | * 67 | * @param context 68 | * @param key The name of the preference to retrieve 69 | * @param defaultValue Value to return if this preference does not exist 70 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with 71 | * this name that is not a string 72 | */ 73 | public static String getString(Context context, String key, String defaultValue) { 74 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 75 | return settings.getString(key, defaultValue); 76 | } 77 | 78 | /** 79 | * put int preferences 80 | * 81 | * @param context 82 | * @param key The name of the preference to modify 83 | * @param value The new value for the preference 84 | * @return True if the new values were successfully written to persistent storage. 85 | */ 86 | public static boolean putInt(Context context, String key, int value) { 87 | SharedPreferences settings = context.getApplicationContext().getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 88 | SharedPreferences.Editor editor = settings.edit(); 89 | editor.putInt(key, value); 90 | return editor.commit(); 91 | } 92 | 93 | /** 94 | * get int preferences 95 | * 96 | * @param context 97 | * @param key The name of the preference to retrieve 98 | * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this 99 | * name that is not a int 100 | * @see #getInt(Context, String, int) 101 | */ 102 | public static int getInt(Context context, String key) { 103 | return getInt(context, key, -1); 104 | } 105 | 106 | /** 107 | * get int preferences 108 | * 109 | * @param context 110 | * @param key The name of the preference to retrieve 111 | * @param defaultValue Value to return if this preference does not exist 112 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with 113 | * this name that is not a int 114 | */ 115 | public static int getInt(Context context, String key, int defaultValue) { 116 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 117 | return settings.getInt(key, defaultValue); 118 | } 119 | 120 | /** 121 | * put long preferences 122 | * 123 | * @param context 124 | * @param key The name of the preference to modify 125 | * @param value The new value for the preference 126 | * @return True if the new values were successfully written to persistent storage. 127 | */ 128 | public static boolean putLong(Context context, String key, long value) { 129 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 130 | SharedPreferences.Editor editor = settings.edit(); 131 | editor.putLong(key, value); 132 | return editor.commit(); 133 | } 134 | 135 | /** 136 | * get long preferences 137 | * 138 | * @param context 139 | * @param key The name of the preference to retrieve 140 | * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this 141 | * name that is not a long 142 | * @see #getLong(Context, String, long) 143 | */ 144 | public static long getLong(Context context, String key) { 145 | return getLong(context, key, -1); 146 | } 147 | 148 | /** 149 | * get long preferences 150 | * 151 | * @param context 152 | * @param key The name of the preference to retrieve 153 | * @param defaultValue Value to return if this preference does not exist 154 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with 155 | * this name that is not a long 156 | */ 157 | public static long getLong(Context context, String key, long defaultValue) { 158 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 159 | return settings.getLong(key, defaultValue); 160 | } 161 | 162 | /** 163 | * put float preferences 164 | * 165 | * @param context 166 | * @param key The name of the preference to modify 167 | * @param value The new value for the preference 168 | * @return True if the new values were successfully written to persistent storage. 169 | */ 170 | public static boolean putFloat(Context context, String key, float value) { 171 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 172 | SharedPreferences.Editor editor = settings.edit(); 173 | editor.putFloat(key, value); 174 | return editor.commit(); 175 | } 176 | 177 | /** 178 | * get float preferences 179 | * 180 | * @param context 181 | * @param key The name of the preference to retrieve 182 | * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this 183 | * name that is not a float 184 | * @see #getFloat(Context, String, float) 185 | */ 186 | public static float getFloat(Context context, String key) { 187 | return getFloat(context, key, -1); 188 | } 189 | 190 | /** 191 | * get float preferences 192 | * 193 | * @param context 194 | * @param key The name of the preference to retrieve 195 | * @param defaultValue Value to return if this preference does not exist 196 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with 197 | * this name that is not a float 198 | */ 199 | public static float getFloat(Context context, String key, float defaultValue) { 200 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 201 | return settings.getFloat(key, defaultValue); 202 | } 203 | 204 | /** 205 | * put boolean preferences 206 | * 207 | * @param context 208 | * @param key The name of the preference to modify 209 | * @param value The new value for the preference 210 | * @return True if the new values were successfully written to persistent storage. 211 | */ 212 | public static boolean putBoolean(Context context, String key, boolean value) { 213 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 214 | SharedPreferences.Editor editor = settings.edit(); 215 | editor.putBoolean(key, value); 216 | return editor.commit(); 217 | } 218 | 219 | /** 220 | * get boolean preferences, default is false 221 | * 222 | * @param context 223 | * @param key The name of the preference to retrieve 224 | * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this 225 | * name that is not a boolean 226 | * @see #getBoolean(Context, String, boolean) 227 | */ 228 | public static boolean getBoolean(Context context, String key) { 229 | return getBoolean(context, key, false); 230 | } 231 | 232 | /** 233 | * get boolean preferences 234 | * 235 | * @param context 236 | * @param key The name of the preference to retrieve 237 | * @param defaultValue Value to return if this preference does not exist 238 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with 239 | * this name that is not a boolean 240 | */ 241 | public static boolean getBoolean(Context context, String key, boolean defaultValue) { 242 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); 243 | return settings.getBoolean(key, defaultValue); 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 |