将自己的SQLite数据库添加到Android应用程序

前端之家收集整理的这篇文章主要介绍了将自己的SQLite数据库添加到Android应用程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们如何将自己的sqlite数据库添加android项目?
尝试这段代码
  1. public class DataBaseHelper extends sqliteOpenHelper {
  2. private Context mycontext;
  3.  
  4. //private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
  5. private static String DB_NAME = "(datbasename).sqlite"; //the extension may be .sqlite or .db
  6. public sqliteDatabase myDataBase;
  7. /*private String DB_PATH = "/data/data/"
  8. + mycontext.getApplicationContext().getPackageName()
  9. + "/databases/";*/
  10.  
  11. public DataBaseHelper(Context context) throws IOException {
  12. super(context,DB_NAME,null,1);
  13. this.mycontext = context;
  14. boolean dbexist = checkdatabase();
  15. if (dbexist) {
  16. //System.out.println("Database exists");
  17. opendatabase();
  18. } else {
  19. System.out.println("Database doesn't exist");
  20. createdatabase();
  21. }
  22.  
  23. }
  24.  
  25. public void createdatabase() throws IOException {
  26. boolean dbexist = checkdatabase();
  27. if (dbexist) {
  28. //System.out.println(" Database exists.");
  29. } else {
  30. this.getReadableDatabase();
  31. try {
  32. copydatabase();
  33. } catch (IOException e) {
  34. throw new Error("Error copying database");
  35. }
  36. }
  37. }
  38. private boolean checkdatabase() {
  39. //sqliteDatabase checkdb = null;
  40. boolean checkdb = false;
  41. try {
  42. String myPath = DB_PATH + DB_NAME;
  43. File dbfile = new File(myPath);
  44. //checkdb = sqliteDatabase.openDatabase(myPath,sqliteDatabase.OPEN_READWRITE);
  45. checkdb = dbfile.exists();
  46. } catch (sqliteException e) {
  47. System.out.println("Database doesn't exist");
  48. }
  49.  
  50. return checkdb;
  51. }
  52. private void copydatabase() throws IOException {
  53.  
  54. //Open your local db as the input stream
  55. InputStream myinput = mycontext.getAssets().open(DB_NAME);
  56.  
  57. // Path to the just created empty db
  58. String outfilename = DB_PATH + DB_NAME;
  59.  
  60. //Open the empty db as the output stream
  61. OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases/(datbasename).sqlite");
  62.  
  63. // transfer byte to inputfile to outputfile
  64. byte[] buffer = new byte[1024];
  65. int length;
  66. while ((length = myinput.read(buffer)) > 0) {
  67. myoutput.write(buffer,length);
  68. }
  69.  
  70. //Close the streams
  71. myoutput.flush();
  72. myoutput.close();
  73. myinput.close();
  74.  
  75. }
  76.  
  77. public void opendatabase() throws sqlException {
  78. //Open the database
  79. String mypath = DB_PATH + DB_NAME;
  80. myDataBase = sqliteDatabase.openDatabase(mypath,sqliteDatabase.OPEN_READWRITE);
  81.  
  82. }
  83.  
  84.  
  85.  
  86. public synchronized void close() {
  87. if (myDataBase != null) {
  88. myDataBase.close();
  89. }
  90. super.close();
  91. }

猜你在找的Sqlite相关文章