如何在android应用程序中导入外部sqlite数据库进行登录?

时间:2015-03-24 09:47:19

标签: android database sqlite

我创建了一个登录布局,但是我需要在sqlite数据库中外部创建登录ID和密码的内置登录ID。 我怎样才能创造出来?这怎么可能? 我已将我的数据库复制到资产文件夹&使用了databasehelper但仍无效。 任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

Assets数据库文件只是一个只读文件,您需要将DB文件复制到您的路径中。您可以使用以下代码复制数据库文件:

public void copyDataBaseFromAsset() throws IOException
{
    File myDir = getFilesDir();
    File dbFolder = new File(myDir, "database");
    if (!dbFolder.exists())
    {
        dbFolder.mkdirs();
    }
    String outFileName = dbFolder.getAbsolutePath() + File.separator + "abc_db.sqlite";
    File file = new File(outFileName);
    if (file.exists())
    {
        Log.e(TAG, "db already exists");
        return;
    }
    InputStream myInput = getAssets().open("abc_db.sqlite");

    // Path to the just created empty db

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the 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();
    Log.e(TAG, "copy done");
}

复制文件后使用文件路径从数据库中获取数据。

已编辑:

将DB路径更改为:

File myDir = getFilesDir();
File dbFolder = new File(myDir, "database");
String outFileName = dbFolder.getAbsolutePath() + File.separator + "abc_db.sqlite";
File file = new File(outFileName);
String DB_PATH = file.getAbsolutePath();