Android 从资产文件夹中读取 sqlite 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20857734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:36:20  来源:igfitidea点击:

Reading sqlite file from asset folder

android

提问by Usman Riaz

i am developing an application in which i want to read an sqlitedatabase file from the asset folder of the project. i have searched the web but nothing found helpful. please help me. Thanks.

我正在开发一个应用程序,我想在其中sqlite从项目的资产文件夹中读取数据库文件。我在网上搜索过,但没有发现任何有用的东西。请帮我。谢谢。

回答by GrIsHu

You cannot directly open files from assets folder. Instead, you need to copy the sqlite database of your assets folder into an internal/external storage and later use the File path to open the file. Try out below code to read the sqlite database from assests and copy it into sdcard to use it.

您不能直接从资产文件夹中打开文件。相反,您需要将资产文件夹的 sqlite 数据库复制到内部/外部存储中,然后使用文件路径打开文件。试试下面的代码从assests读取sqlite数据库并将其复制到sdcard中以使用它。

public class DataBaseHelper extends SQLiteOpenHelper {
   private Context mycontext;
   private static String DB_NAME = "(datbasename).sqlite";
   private static String DB_PATH ="/data/data/"+BuildConfig.APPLICATION_ID+"/databases/";
   public SQLiteDatabase myDataBase;

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() {

    boolean checkdb = false;
    try {
        String myPath = DB_PATH + DB_NAME;
        File dbfile = new File(myPath);
        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(outfilename);

    // 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();
}
}

回答by CommonsWare

Please use SQLiteAssetHelper, which has all the code that you need to install a pre-packaged database when your app is first run.

使用SQLiteAssetHelper,其中包含首次运行应用程序时安装预打包数据库所需的所有代码。

回答by A.J.Bauer

Basically you can get an InputStream (from the AssetManager open function) for a file name and write it to an OutputStream.

基本上,您可以获得文件名的 InputStream(来自 AssetManager open 函数)并将其写入 OutputStream。

InputStream inputStream = getAssets().open(fileName);

If you create your database using openOrCreateDatabase you might want to put the database in the databases folder...

如果您使用 openOrCreateDatabase 创建数据库,您可能希望将数据库放在数据库文件夹中...

    String fileName = "MySQLiteDB.db";
    File file = getDatabasePath(fileName );
    if (!file.exists()) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }

        InputStream inputStream = getAssets().open(DATABASE_NAME);
        OutputStream outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024 * 8];
        int numOfBytesToRead;
        while((numOfBytesToRead = inputStream.read(buffer)) > 0)
        outputStream.write(buffer, 0, numOfBytesToRead);
        inputStream.close();
        outputStream.close();
    }

    db = SQLiteDatabase.openOrCreateDatabase(file, null);

回答by Bhushan Shirsath

1. Make the SQLite database file.

?    If you don't have a sqlite manager I recommend you to download the opensource SQLite Database Browser available for Win/Linux/Mac. Make database file.
?    

2. Use this database in your Android application.
?    Now put your database file in the "assets" folder of your project and create a Database Helper class by extending the SQLiteOpenHelper class


  //Constructor
  public Databasehelper(Context context)
  {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
  }

  //Create a empty database on the system
  public void createDatabase() throws IOException
  {
        boolean dbExist = checkDataBase();

        if(dbExist)
        {
              Log.v("DB Exists", "db exists");
              // By calling this method here onUpgrade will be called on a
              // writeable database, but only if the version number has been
              // bumped
              //onUpgrade(myDataBase, DATABASE_VERSION_old, DATABASE_VERSION);
        }

        boolean dbExist1 = checkDataBase();
        if(!dbExist1)
        {
              this.getReadableDatabase();
              try
              {
                    this.close();    
                    copyDataBase();
              }
              catch (IOException e)
              {
                    throw new Error("Error copying database");
           }
        }
  }

  //Check database already exist or not
  private boolean checkDataBase()
  {
        boolean checkDB = false;
        try
        {
              String myPath = DATABASE_PATH + DATABASE_NAME;
              File dbfile = new File(myPath);
              checkDB = dbfile.exists();
        }
        catch(SQLiteException e)
        {
        }
        return checkDB;
  }

  //Copies your database from your local assets-folder to the just created empty database in the system folder
  private void copyDataBase() throws IOException
  {
        String outFileName = DATABASE_PATH + DATABASE_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0)
        {
              myOutput.write(buffer, 0, length);
        }
        myInput.close();
        myOutput.flush();
        myOutput.close();
  }

  //delete database
  public void db_delete()
  {
        File file = new File(DATABASE_PATH + DATABASE_NAME);
        if(file.exists())
        {
              file.delete();
              System.out.println("delete database file.");
        }
  }

  //Open database
  public void openDatabase() throws SQLException
  {
        String myPath = DATABASE_PATH + DATABASE_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
  }

  public synchronized void closeDataBase()throws SQLException
  {
        if(myDataBase != null)
              myDataBase.close();
        super.close();
  }

  public void onCreate(SQLiteDatabase db)
  {
  }

  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
  {    
        if (newVersion > oldVersion)
        {
              Log.v("Database Upgrade", "Database version higher than old.");
              db_delete();
        }
  }

//add your public methods for insert, get, delete and update data in database. }

//在数据库中添加用于插入、获取、删除和更新数据的公共方法。}

enter code here

在此处输入代码

ReferLink:http://androidtutorials60.blogspot.in/2013/03/1.html

参考链接:http: //androidtutorials60.blogspot.in/2013/03/1.html