我的数据库没有出现

时间:2017-03-06 17:48:59

标签: java android

我创建了下一个数据库:encuestadoSQLiteHelper encuestado = new encuestadoSQLiteHelper(this, "DBEncuestado", null, 1); final SQLiteDatabase db = encuestado.getWritableDatabase();

在这里:

Intent pas = new Intent(encuesta.this, MainActivity.class);
                Toast.makeText(context,"¡Encuesta enviada!",Toast.LENGTH_LONG).show();
                startActivity(pas);
                String nombre = "Pablo";
                db.execSQL("INSERT INTO Encuestado (nombre) " +
                        "VALUES ('" + nombre +"')");
                db.close();

未创建数据库,因为我转到documents / sdcard / data /,我的应用程序包不会出现。我需要帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

已创建数据库,但用户无法访问数据库。只有创建此数据库的应用程序才能访问它。

如果您想访问数据库,那么有两种方法,根据您的手机或编写代码将数据库从您的应用程序复制到另一个文件夹。

修改

将数据库从代码复制到Sdcard

try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "/data/"+YOUR_PACKAGE_NAME+"/databases/"+DATABASE_NAME;
            String backupDBPath = "backdatabase.sqlite";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
     System.out.println("error in data base copy:"+e);
    }

您还有权使用清单文件访问SDCard:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

答案 1 :(得分:0)

您可以使用此代码导出要在存储中访问的文件

private void exportDB() throws Exception {
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                File sd = context.getExternalCacheDir();
                File data = Environment.getDataDirectory();
                FileChannel source = null;
                FileChannel destination = null;
                StringBuilder localPath = new StringBuilder();
                localPath.append(context.getExternalCacheDir().toString()).append("/");
                String currentDBPath = "/data/" + YOUR_PACKAGE_HERE + "/databases/" + DATABASE_NAME;
                String backupDBPath = DATABASE_NAME;
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);
                source = new FileInputStream(currentDB).getChannel();
                destination = new FileOutputStream(backupDB).getChannel();
                destination.transferFrom(source, 0, source.size());
                source.close();
                destination.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}