Java 在移动设备上找不到sqlite db,但可以在emulator上工作

Java 在移动设备上找不到sqlite db,但可以在emulator上工作,java,android,sqlite,Java,Android,Sqlite,我创建了一个sqlite数据库,它由一个表组成,数据库中填充了大约2000行 我能够查询这个表,当我通过模拟器进行查询时,一切都正常工作 但当我在移动设备上测试它时,它会抛出以下错误: android.database.sqlite.SQLiteException:没有这样的表:person(代码 1) :,编译时:从rowid=292的人员中选择姓名 当我在一台设备上尝试它时,我希望填充的sqlite数据库在我的设备上自动可用,但基于上述错误,看起来情况并非如此 我确实查看了过去的问题,但它们

我创建了一个sqlite数据库,它由一个表组成,数据库中填充了大约2000行

我能够查询这个表,当我通过模拟器进行查询时,一切都正常工作

但当我在移动设备上测试它时,它会抛出以下错误:

android.database.sqlite.SQLiteException:没有这样的表:person(代码 1) :,编译时:从rowid=292的人员中选择姓名

当我在一台设备上尝试它时,我希望填充的sqlite数据库在我的设备上自动可用,但基于上述错误,看起来情况并非如此

我确实查看了过去的问题,但它们与我的问题不匹配

  • 我没有为db存储位置设置自己的路径

    当我在设备文件资源管理器下查看时,数据库的路径是 /data/data/com.somepackage.myappname/databases/person

  • 我已尝试卸载应用程序,然后重新安装,但没有任何区别

  • 我的sdk设置详细信息(如果相关)

    明斯克版本16

    targetSdkVersion 27

    移动设备:使用安卓8.0.0版

    请告知我如何在安装应用程序时(当我单击在Android Studio上运行时)让数据库自动随应用程序一起提供

    这就是我将数据加载到数据库中的方式。这只运行了一次,我现在已经注释掉了这段代码

        try {
            SQLiteDatabase database = this.openOrCreateDatabase("person", MODE_PRIVATE, null);
            database.execSQL("DROP TABLE IF EXISTS person");
            database.execSQL("CREATE TABLE IF NOT EXISTS person (name VARCHAR, name_size INT(8))");
    
            BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("person.txt")));
            String line;
            while ((line = br.readLine()) != null) {
                String sql = "INSERT INTO person (name, name_size) VALUES ('" + line + "', " + line.length() + ")";
                database.execSQL(sql);
            }database.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }  
    
    我使用onCreate方法初始化数据库

    database = this.openOrCreateDatabase("person", MODE_PRIVATE, null);
    
    单击按钮时,将执行以下方法。 该错误发生在该方法的第一行

    private String retrieveNextPerson(int randomIndex){
            //error on this raw query
            Cursor cursor = database.rawQuery("SELECT name from person WHERE rowid = " + randomIndex, null);
            int wordIndex = cursor.getColumnIndex("name");
            cursor.moveToFirst();
            return cursor.getString(wordIndex);
        }
    

    假设您没有错误地认为在模拟器(或任何设备)上运行应用程序会改变软件包,从而使发行版包含已填充的数据库

    • 分发预填充的数据库涉及

      • a) 填充数据库(通常使用SQLite管理工具)
      • b) 将此文件(作为数据库的文件)复制到assets文件夹中,然后:-
      • c) 从资产文件夹中检索此

        • 使用使这变得容易,注意到使用
          SQLiteAssethelper
          DB文件需要存在于databases文件夹中(您很可能需要创建此文件夹))
    那么我怀疑您过早地调用了:-

     database = this.openOrCreateDatabase("person", MODE_PRIVATE, null);
    
    这样做将创建不带person表的person数据库,从而导致前面描述的故障

    您需要在使用上述行之前加载数据

    或者,如果在
    database=this.openOrCreateDatabase(“person”,MODE_PRIVATE,null)之后立即添加以下代码

    • 注意可以看出,person.txt被“错误地”命名为notperson.txt,以强制执行错误
    注意:在此阶段,数据库将存在(由于
    openOrCreateDatabase
    ),它将包含两个表(sqlite\u master和android\u元数据),但不包含person表,例如:-

    但是,创建正确的资产文件person.txt(将notperson.txt重命名为person.text)将导致创建表并加载数据:-

    e、 g.如果person.txt为:-

    然后运行应用程序将生成包含以下内容的日志:-

    06-10 04:39:04.277 3325-3325/? D/PERSON ROW COUNT: The number of rows in the person table is 11
    

    谢谢你的回复。不确定您是否错过了我提到的数据库创建已经完成的部分,并且该部分已经被注释掉。我调用了一次db创建并加载了数据,db现在就在应用程序中(至少对于emulator是这样)。你提到的初始化应该打开一个现有的数据库和一个现有的表,因此我不认为这是过早的。不,我没有遗漏任何部分。然而,答案将被编辑,包括一个相当坚实的返工,应该克服你的问题。
    public class MainActivity extends AppCompatActivity {
    
        public static final String DBNAME = "person";
        public static final String TBNAME = "person";
        public static final String COL_NAME = "name";
        public static final String COL_NAME_SIZE = "name_size";
        public static final String ASSET_FILENAME = "person.txt";
    
        public static final String SQLITE_MASTER_TABLE = "sqlite_master";
        public static final String COL_SQLITE_MATSER_NAME = "name";
    
        static final int MIMINUM_ROWS_IN_PERSONTABLE = 1;
    
        SQLiteDatabase db;
        BufferedReader br;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            checkPersonTable(); // Notes sets db either way
    
            // FOR TESTING
            long rows_in_person_table = DatabaseUtils.queryNumEntries(db,TBNAME);
            Log.d(
                    "PERSON ROW COUNT",
                    "The number of rows in the " +
                            TBNAME +
                            " table is " +
                            String.valueOf(rows_in_person_table)
            );
        }
    
    
        private void checkPersonTable() {
    
            db = this.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
            // Database will now exist but it may or may not contain the person table so check sqlite_master
            Cursor csr = db.query(
                    SQLITE_MASTER_TABLE,
                    new String[]{COL_SQLITE_MATSER_NAME},
                            COL_SQLITE_MATSER_NAME + "=?",
                            new String[]{TBNAME},
                            null,null,null
            );
            // Cursor will contain 1 row if the person table exists so check count
            int person_table_count = csr.getCount();
            csr.close();
            // Before attemtping to create the Person table ensure that the assets file exists
            // If not then throw a RunTime exception
    
            if (person_table_count < 1) {
                try {
                    if (!Arrays.asList(getResources().getAssets().list("")).contains(ASSET_FILENAME)) {
                        StringBuilder sb = new StringBuilder();
                        throw new RuntimeException("Asset file " +
                                ASSET_FILENAME +
                                " not found in the assets folder." +
                                " The following assets were found" +
                                sb
                        );
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            if (person_table_count < 1) {
                db.execSQL("CREATE TABLE IF NOT EXISTS " + TBNAME +
                        "(" +
                        COL_NAME + " TEXT," +
                        COL_NAME_SIZE + " INTEGER" +
                        ")"
                );
                loadPersonsFromAssets();
            } else {
                // <<<<<<<<<< NOTE Optional will load data from assets if miminum nuber of rows
                //                 aren't in the person table
                if (DatabaseUtils.queryNumEntries(db,TBNAME) < MIMINUM_ROWS_IN_PERSONTABLE) {
                    loadPersonsFromAssets();
                }
            }
        }
    
        // Load the person table from the Assets File
        private void loadPersonsFromAssets() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open(ASSET_FILENAME)));
                String line, sql;
                int lines_read = 0;
                db.beginTransaction();
                while ((line = br.readLine()) != null) {
                    sql = "INSERT INTO " + TBNAME + " VALUES('" + line + "'," + String.valueOf(line.length()) + ")";
                    db.execSQL(sql);
                    lines_read++;
                }
                db.setTransactionSuccessful();
                db.endTransaction();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Asset File " + ASSET_FILENAME + " not found in the assets folder.");
            }
        }
    }
    
    06-10 03:58:43.503 3097-3097/personthing.so50777840 E/AndroidRuntime: FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{personthing.so50777840/personthing.so50777840.MainActivity}: java.lang.RuntimeException: Asset file person.txt not found in the assets folder. The following assets were found
             found asset file :- images
             found asset file :- notperson.txt
             found asset file :- sounds
             found asset file :- webkit
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.RuntimeException: Asset file person.txt not found in the assets folder. The following assets were found
             found asset file :- images
             found asset file :- notperson.txt
             found asset file :- sounds
             found asset file :- webkit
            at personthing.so50777840.MainActivity.checkPersonTable(MainActivity.java:83)
            at personthing.so50777840.MainActivity.onCreate(MainActivity.java:39)
            at android.app.Activity.performCreate(Activity.java:5008)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
                ... 11 more
    
    06-10 04:39:04.277 3325-3325/? D/PERSON ROW COUNT: The number of rows in the person table is 11