java—使用现有数据库在android应用程序中显示数据

t40tm48m  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(429)

嗨,我是android开发的新手。我已经创建了sqlite数据库,并将其保存在androidstudio的assets文件夹中。我的应用程序必须使用现有的数据库,而不是创建一个新的。我面临的问题是,当我想在屏幕上显示数据时,它会向执行sql语句的游标抛出一个错误。请帮忙。
数据库的名称是 test.db 表名是 MASTER . 这是我的databasehelper类

public class DataBaseHelper extends SQLiteOpenHelper {
    private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
    //destination path (location) of our database on device
    private static String DB_PATH = "";
    private static String DB_NAME ="test,db";// Database name
    private SQLiteDatabase mDataBase;
    private final Context mContext;

    public DataBaseHelper(Context context)
    {
        super(context, DB_NAME, null, 1);// 1? Its database Version
        if(android.os.Build.VERSION.SDK_INT >= 17){
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        }
        else
        {
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        }
        this.mContext = context;
    }

    public void createDataBase() throws IOException
    {
        //If the database does not exist, copy it from the assets.

        boolean mDataBaseExist = checkDataBase();
        if(!mDataBaseExist)
        {
            this.getReadableDatabase();
            this.close();
            try
            {
                //Copy the database from assests
                copyDataBase();
                Log.e(TAG, "createDatabase database created");
            }
            catch (IOException mIOException)
            {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    //Check that the database exists here: /data/data/your package/databases/Da Name
    private boolean checkDataBase()
    {
        File dbFile = new File(DB_PATH + DB_NAME);
        //Log.v("dbFile", dbFile + "   "+ dbFile.exists());
        return dbFile.exists();
    }

    //Copy the database from assets
    private void copyDataBase() throws IOException
    {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer))>0)
        {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    //Open the database, so we can query it
    public boolean openDataBase() throws SQLException
    {
        String mPath = DB_PATH + DB_NAME;
        //Log.v("mPath", mPath);
        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        return mDataBase != null;
    }

    @Override
    public synchronized void close()
    {
        if(mDataBase != null)
            mDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

这是我的testadapter课程

public class TestAdapter
    {
        protected static final String TAG = "DataAdapter";

        private final Context mContext;
        private SQLiteDatabase mDb;
        private DataBaseHelper mDbHelper;

        public TestAdapter(Context context)
        {
            this.mContext = context;
            mDbHelper = new DataBaseHelper(mContext);
        }

        public TestAdapter createDatabase() throws SQLException
        {
            try
            {
                mDbHelper.createDataBase();
            }
            catch (IOException mIOException)
            {
                Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
                throw new Error("UnableToCreateDatabase");
            }
            return this;
        }

        public TestAdapter open() throws SQLException
        {
            try
            {
                mDbHelper.openDataBase();
                mDbHelper.close();
                mDb = mDbHelper.getReadableDatabase();
            }
            catch (SQLException mSQLException)
            {
                Log.e(TAG, "open >>"+ mSQLException.toString());
                throw mSQLException;
            }
            return this;
        }

        public void close()
        {
            mDbHelper.close();
        }

        public Cursor getTestData() {
            try
            {
                String sql ="SELECT * FROM MASTER;";

                Cursor mCur = mDb.rawQuery(sql, null);
                if (mCur!=null)
                {
                    mCur.moveToNext();
                }
                return mCur;
            }
            catch (SQLException mSQLException)
            {
                Log.e(TAG, "getTestData >>"+ mSQLException.toString());
                throw mSQLException;
            }
        }
    }

这是我的主要活动课

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button=findViewById(R.id.submit);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TestAdapter mDbHelper = new TestAdapter(MainActivity.this);
                mDbHelper.createDatabase();
                mDbHelper.open();
                Cursor testdata = mDbHelper.getTestData();
                Toast.makeText(MainActivity.this,testdata.getString(0),Toast.LENGTH_SHORT).show();
                mDbHelper.close();
            }
        });

    }
}

这是logcat

2019-02-04 15:47:30.227 2594-2594/com.example.myapplication E/SQLiteLog: (1) no such table: MASTER
2019-02-04 15:47:30.228 2594-2594/com.example.myapplication E/DataAdapter: getTestData >>android.database.sqlite.SQLiteException: no such table: MASTER (code 1): , while compiling: SELECT * FROM MASTER;
2019-02-04 15:47:30.228 2594-2594/com.example.myapplication D/AndroidRuntime: Shutting down VM
2019-02-04 15:47:30.242 2594-2594/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 2594
    android.database.sqlite.SQLiteException: no such table: MASTER (code 1): , while compiling: SELECT * FROM MASTER;
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
        at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
        at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1392)
        at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1331)
        at com.example.myapplication.TestAdapter.getTestData(TestAdapter.java:63)
        at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:38)
        at android.view.View.performClick(View.java:6297)
        at android.view.View$PerformClick.run(View.java:24797)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6626)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)

logcat说没有 MASTER 但当我通过sqlitedb浏览器查看数据库时,它当时就在那里。

eanckbw9

eanckbw91#

我相信你的主要问题是 private static String DB_NAME ="test,db";// Database name 而不是 private static String DB_NAME ="test.db";// Database name 那就是你用逗号编码 , 而不是一段时间 . 因此,在assets文件夹中的数据库文件将找不到,因此不会被复制。
当第一次运行文件测试时,由于使用了 this.getReadableDatabase(); ,这将导致创建数据库,该数据库将为空,因此对于后续运行,不会尝试从assets文件夹复制文件,因为数据库存在,因此当数据库为空时,访问该表的尝试将失败,因为该表不存在。
请注意,getredabledatabase在大多数情况下实际上会获得一个可写数据库
创建和/或打开数据库。这将是getwritabledatabase()返回的相同对象,除非某些问题(如磁盘已满)要求以只读方式打开数据库。在这种情况下,将返回一个只读数据库对象。如果问题已解决,则将来对getwritabledatabase()的调用可能会成功,在这种情况下,将关闭只读数据库对象,并在将来返回读/写对象。GetReadable数据库
我相信使用 getReadableDatabase 仅用于避免一个问题,即最初数据库文件夹不存在,因此尝试从资产复制文件失败,因为父文件夹不存在。更好的解决办法是不使用 getReadableDatabase 但是要检查目录是否存在,如果不存在,就创建它。
这种用法 getReabableDatabase 在使用android9+时引入了更大的问题,因为默认情况下使用wal(写前日志记录)会产生额外的文件(数据库名称后缀为-shm和-wal)。
因此,使用:-

//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    if (dbFile.exists()) return true;
    if (!dbFile.getParentFile().exists()) dbFile.getParentFile().mkdirs();
    return false;
}

不再需要使用 getReabableDatabase 而且,即使由于资产文件不存在而导致随后的复制失败,实际创建一个数据库文件也会带来复杂性。
为了更加小心地处理可能无意中存在的-shm和-wal文件,甚至可以将上述内容扩展到:-

private boolean checkDataBase()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    if (dbFile.exists()) return true;
    if (!dbFile.getParentFile().exists()) dbFile.getParentFile().mkdirs();
    if (new File(DB_PATH + DB_NAME + "-shm").exists())
        new File(DB_PATH + DB_NAME + "-shm").delete();
    if ((new File(DB_PATH + DB_NAME + "-wal")).exists())
        new File(DB_PATH + DB_NAME + "-wal").delete();
    return false;
}

一般使用 DB_PATH = context.getApplicationInfo().dataDir + "/databases/"; 不是推荐的,而是更具体的 DB_PATH = mContext.getDatabasePath(DB_NAME).getPath(); 建议使用,因为不需要硬编码文件说明符和文件夹名称。
这样的数据库帮助器可能是更好的总体数据库帮助器:-

public class DataBaseHelper extends SQLiteOpenHelper {
    private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
    //destination path (location) of our database on device
    private static String DB_PATH = "";
    private static String DB_NAME ="test.db";// Database name //<<<<<<<<<< CHANGED TO FIX PRIMARY ISSUE
    private SQLiteDatabase mDataBase;
    private final Context mContext;

    public DataBaseHelper(Context context)
    {
        super(context, DB_NAME, null, 1);// 1? Its database Version
        this.mContext = context;
        DB_PATH = mContext.getDatabasePath(DB_NAME).getPath();
    }

    public void createDataBase() throws IOException
    {
        //If the database does not exist, copy it from the assets.

        boolean mDataBaseExist = checkDataBase();
        if(!mDataBaseExist)
        {
            //this.getReadableDatabase(); //<<<<<<<<<< REMOVED (commented out)
            //this.close(); //<<<<<<<<<< REMOVED ()commented out
            try
            {
                //Copy the database from assests
                copyDataBase();
                Log.e(TAG, "createDatabase database created");
            }
            catch (IOException mIOException)
            {
                mIOException.printStackTrace(); //<<<<<<<<<< might as well include the actual cause in the log
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    //Check that the database exists here: /data/data/your package/databases/Da Name
    private boolean checkDataBase()
    {
        File dbFile = new File(DB_PATH); //<<<<<<<<<< just the path used
        if (dbFile.exists()) return true; //<<<<<<<<<< return true of the db exists (see NOTE001)
        if (!dbFile.getParentFile().exists()) dbFile.getParentFile().mkdirs();
        if (new File(DB_PATH + "-shm").exists())
            new File(DB_PATH + "-shm").delete();
        if ((new File(DB_PATH + "-wal")).exists())
            new File(DB_PATH + "-wal").delete();
        return false;
    }

    /**NOTE001
     *  Just checking the file does leave scope for a non sqlite file to be copied from the assets folder
     *  and be copied resulting in an exception. The above could be extended to apply additional checks
     *  if considered required e.g. checking the first sixteen bytes for The header string: "SQLite format 3\000"
     */

    //Copy the database from assets
    private void copyDataBase() throws IOException
    {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH; //<<<<<<<<<< just the path used
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer))>0)
        {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    //Open the database, so we can query it
    public boolean openDataBase() throws SQLException
    {
        String mPath = DB_PATH;
        //Log.v("mPath", mPath);
        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        return mDataBase != null;
    }

    /**
     * Note this can be added and the line uncommented (see below) to disable WAL logging which
     * from Anroid 9 (Pie) is the default
     */
    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        // db.disableWriteAheadLogging(); //<<<<<<<<<< uncomment if you want to not use WAL but use the less efficient joutnal mode.
    }

    @Override
    public synchronized void close()
    {
        if(mDataBase != null)
            mDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

注意:请参阅代码中的注解

额外/测试

如果使用了上述内容(在删除应用程序的数据或卸载应用程序以删除空数据库之后),但资产文件夹中没有合适的文件(test,db unchanged for the test),则上述内容将导致更具解释性的结果:-

02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err: java.io.FileNotFoundException: test,db
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at android.content.res.AssetManager.openAsset(Native Method)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:313)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:287)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at mjt.so54513838.DataBaseHelper.copyDataBase(DataBaseHelper.java:75)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at mjt.so54513838.DataBaseHelper.createDataBase(DataBaseHelper.java:42)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at mjt.so54513838.TestAdapter.createDatabase(TestAdapter.java:29)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at mjt.so54513838.MainActivity$1.onClick(MainActivity.java:23)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at android.view.View.performClick(View.java:4780)
02-05 10:17:03.513 5502-5502/mjt.so54513838 W/System.err:     at android.view.View$PerformClick.run(View.java:19866)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at android.os.Looper.loop(Looper.java:135)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5254)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
02-05 10:17:03.514 5502-5502/mjt.so54513838 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
02-05 10:17:03.514 5502-5502/mjt.so54513838 D/AndroidRuntime: Shutting down VM
02-05 10:17:03.514 5502-5502/mjt.so54513838 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: mjt.so54513838, PID: 5502
    java.lang.Error: ErrorCopyingDataBase
        at mjt.so54513838.DataBaseHelper.createDataBase(DataBaseHelper.java:48)
        at mjt.so54513838.TestAdapter.createDatabase(TestAdapter.java:29)
        at mjt.so54513838.MainActivity$1.onClick(MainActivity.java:23)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

如果应用程序然后再次运行,没有任何更改,那么上述情况也会发生,而不是更混乱的表找不到。

注意在运行上述代码之前,或者即使只是更改test,db to test.db数据库文件也必须删除。这可以通过删除/清除应用程序的数据或卸载应用程序轻松实现。

上面的内容已经在android5.0(棒棒糖)(api 22)和android9(pie)(api 28)上进行了测试,结果是toast显示了一个表(尽管为了方便起见,表从master改为sqlite\u master(在使用现有数据库文件时不必创建数据库文件)。

yqhsw0fo

yqhsw0fo2#

直接将数据路径设置为字符串,希望它能工作

private final static String DATABASE_PATH ="/data/data/com.yourpackagename/databases/";
public SQLiteDatabase openDatabase() throws SQLException
    {   String myPath = DATABASE_PATH + "DB_NAME";myDataBase = SQLiteDatabase.openOrCreateDatabase(myPath, null, null);
        return myDataBase;
    }`

相关问题