【问题标题】:Where should I put a sqlite file in source android app [duplicate]我应该将sqlite文件放在源android应用程序的哪里[重复]
【发布时间】:2014-01-14 20:24:42
【问题描述】:

我是一名新的安卓开发者。
我有一个现有的 SQLite 数据库。
我的问题是:我应该把它放在我的源代码的哪里?
还有:我想在安装时将它复制到设备上。

请帮忙

谢谢

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    你有什么。

    您必须将外部 sqlite 数据库文件放入 assets 文件夹并复制到 SD 卡 并访问它。

    例如,

    只创建一个名为的类

    DBConnect.java

    package com.appgiudeextra.Database;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;
    
    import com.appguideextra.Items.MasterItem;
    
    public class DBConnect extends SQLiteOpenHelper {
    public int GetCursor;
    // ****************** Declare all the global variable
    // ****************************//
    private Context myContext;
    public String DB_PATH = "data/data/com.xyz/databases/"; // path
    // of
    // your
    // datbase
    public static String DB_NAME = "xyz.sqlite";// your database name
    static String ASSETS_DB_FOLDER = "db";
    private SQLiteDatabase db;
    
    public DBConnect(Context context, String db_name) {
        super(context, db_name, null, 2);
        if (db != null && db.isOpen())
            close();
    
        this.myContext = context;
        DB_NAME = db_name;
    
        try {
            createDataBase();
            openDataBase();
        } catch (IOException e) {
            // System.out.println("Exception in creation of database : "+
            // e.getMessage());
            e.printStackTrace();
        }
    
    }
    
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
    
        if (dbExist) {
            // System.out.println("Database Exist");
        } else {
            this.getReadableDatabase();
    
            try {
                copyDatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }
    
    private void copyDatabase() throws IOException {
        InputStream input = myContext.getAssets().open(DB_NAME);
        String outputFileName = DB_PATH + DB_NAME;
        OutputStream output = new FileOutputStream(outputFileName);
    
        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    
        // Close the streams
        output.flush();
        output.close();
        input.close();
        // System.out.println(DB_NAME + "Database Copied !");
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
    
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
    }
    
    public void openDataBase() throws SQLException {
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }
    
    public boolean isOpen() {
        if (db != null)
            return db.isOpen();
        return false;
    }
    
    @Override
    public synchronized void close() {
        if (db != null)
            db.close();
        super.close();
    }
    
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            // System.out.println("My Pathe is:- " + myPath);
            // System.out.println("Open");
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
            // System.out.println("checkDB value:" + checkDB);
            // System.out.println("My Pathe is:- " + myPath);
        } catch (Exception e) {
            // database does't exist yet.
        }
    
        if (checkDB != null) {
            // System.out.println("Closed");
            checkDB.close();
            // System.out.println("My db is:- " + checkDB.isOpen());
        }
    
        return checkDB != null ? true : false;
    }
    
    public Cursor execCursorQuery(String sql) {
        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, null);
            GetCursor = cursor.getCount();
            Log.i("Inside execCursorQuery try", sql);
        } catch (Exception e) {
            Log.i("Inside execCursorQuery exception", e.getMessage());
        }
        return cursor;
    }
    
    public void execNonQuery(String sql) {
        try {
            db.execSQL(sql);
            // Log.d("SQL", sql);
        } catch (Exception e) {
            // Log.e("Err", e.getMessage());
        } finally {
            // closeDb();
        }
    }
    
    
    }
    

    然后将此类访问到您的 Activity。

    【讨论】:

      【解决方案2】:
       My question is: where should I put it in my source?
      

      您可以将数据库放入应用程序的 assets 文件夹中,然后将其复制到 sdcard 并使用它。

      尝试下面的代码将数据库从 assets 文件夹复制到 sdcard。

      DataBaseHelper.java

      public class DataBaseHelper extends SQLiteOpenHelper {
          private Context mycontext;
      
          //private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
          private static String DB_NAME = "(datbasename).sqlite";//the extension may be .sqlite or .db
          public SQLiteDatabase myDataBase;
          /*private String DB_PATH = "/data/data/"
                              + mycontext.getApplicationContext().getPackageName()
                              + "/databases/";*/
      
          public DataBaseHelper(Context context) throws IOException {
              super(context,DB_NAME,null,1);
              this.mycontext=context;
              boolean dbexist = checkdatabase();
              if (dbexist) {
                  //System.out.println("Database exists");
                  opendatabase(); 
              } else {
                  System.out.println("Database doesn't exist");
                  createdatabase();
              }
          }
      
          public void createdatabase() throws IOException {
              boolean dbexist = checkdatabase();
              if(dbexist) {
                  //System.out.println(" Database exists.");
              } else {
                  this.getReadableDatabase();
                  try {
                      copydatabase();
                  } catch(IOException e) {
                      throw new Error("Error copying database");
                  }
              }
          }   
      
          private boolean checkdatabase() {
              //SQLiteDatabase checkdb = null;
              boolean checkdb = false;
              try {
                  String myPath = DB_PATH + DB_NAME;
                  File dbfile = new File(myPath);
                  //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
                  checkdb = dbfile.exists();
              } catch(SQLiteException e) {
                  System.out.println("Database doesn't exist");
              }
              return checkdb;
          }
      
          private void copydatabase() throws IOException {
              //Open your local db as the input stream
              InputStream myinput = mycontext.getAssets().open(DB_NAME);
      
              // Path to the just created empty db
              String outfilename = DB_PATH + DB_NAME;
      
              //Open the empty db as the output stream
              OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases   /(datbasename).sqlite");
      
              // transfer byte to inputfile to outputfile
              byte[] buffer = new byte[1024];
              int length;
              while ((length = myinput.read(buffer))>0) {
                  myoutput.write(buffer,0,length);
              }
      
              //Close the streams
              myoutput.flush();
              myoutput.close();
              myinput.close();
          }
      
          public void opendatabase() throws SQLException {
              //Open the database
              String mypath = DB_PATH + DB_NAME;
              myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
          }
      
          public synchronized void close() {
              if(myDataBase != null) {
                  myDataBase.close();
              }
              super.close();
          }
      
      }
      

       I want copy it to device upon installation.
      

      在您的启动器活动中创建DataBaseHelper 类的实例,如下所示,它将直接复制数据库。

      DataBaseHelper dbhelper=new DataBaseHelper(MyActivity.this);
      

      【讨论】:

        【解决方案3】:

        您可以将您的数据库放在 assets 文件夹中,然后将该数据库复制到 sdcard 并从 sdcard 中检索该数据库:

        复制数据库:

        public static void copyDataBase(Context mActivity) throws IOException {
                InputStream myInput = new FileInputStream(new File("/data/data/"
                        + mActivity.getPackageName() + "/databases/" + "aman36.sqlite"));
                File files = new File("/sdcard/files/");
                files.mkdirs();
                String outFileName = "/sdcard/files/aman36.sqlite";
                OutputStream myOutput = new FileOutputStream(outFileName);
                byte[] buffer = new byte[1024];
                int bufferLength;
                while ((bufferLength = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, bufferLength);
                }
                myOutput.flush();
                myOutput.close();
                myInput.close();
            }
        

        你可以访问你的路径来检索数据库->sdcard->files->aman36.sqlite

        【讨论】:

          【解决方案4】:

          将你的 database.sqlite 文件放在项目目录的资产文件夹中,并使用this 检索它 链接。

          【讨论】:

            猜你喜欢
            • 2010-09-05
            • 2011-06-06
            • 1970-01-01
            • 2014-01-30
            • 1970-01-01
            • 2010-10-02
            • 1970-01-01
            • 2015-02-21
            • 2022-09-29
            相关资源
            最近更新 更多