无法在外部存储器中创建数据库在Android 11+

hwamh0ep  于 2023-03-16  发布在  Android
关注(0)|答案(1)|浏览(325)

我想在我的应用程序中创建一个数据库。我使用了此代码,它在Android 9及更低版本上正常工作,但在Android 10+上,我遇到了崩溃,不仅没有创建数据库,而且在外部存储中也没有创建文件目录。

机器人清单.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.miplan">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    tools:ignore="ScopedStorage">
    
</uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MiPlan">
        <activity
            android:name=".SplashActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="false" />
        <activity
            android:name=".LogoActivity"
            android:exported="true">

        </activity>
    </application>

</manifest>

这是我的数据库助手

package com.example.miplan;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class MyDatabaseHelper extends SQLiteOpenHelper {

  private static final String DB_NAME = "myDatabase.SqLite";
  private static final int DB_VERSION = 1;

  public MyDatabaseHelper(@Nullable Context context) {
    super(context, SplashActivity.DB_DIR + "/" + DB_NAME, null, DB_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    String query = " CREATE TABLE 'person' (" +
      "'personId' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , " +
      "'firstName' TEXT, " +
      "'lastName' TEXT, " +
      "'gender' INTEGER, " +
      "'email' TEXT UNIQUE, " +
      "'phoneNumber' TEXT UNIQUE)";
    // db.execSQL(query);
  }

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

}

启动活动

package com.example.miplan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends AppCompatActivity {
  public static String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
  public static String BRAND = SDCARD + "/Self-learn";
  public static String APP_DIR = BRAND + "/MiPlan";
  public static String DB_DIR = APP_DIR + "/db";
  public static SQLiteDatabase database;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_begin);
    int grantResult = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (grantResult == PackageManager.PERMISSION_GRANTED) {
      createAppDir();
    } else {
      askUserForPermission();
    }
  }

  private void askUserForPermission() {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
      case 100:
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {

          AlertDialog.Builder dialog = new AlertDialog.Builder(this);
          dialog.setTitle("Error").setMessage("Write on External Storage is needed for this app").setPositiveButton("ask again", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
              askUserForPermission();
            }
          }).setCancelable(false).create().show();

        } else {
          createAppDir();
        }
        break;
    }
  }

  private void createAppDir() {
    File file = new File(DB_DIR);
    if (!file.exists()) {
      file.mkdirs();
      createDatabase();
    }
    createDatabase();

  }

  public void createDatabase() {
    MyDatabaseHelper dbHelper = new MyDatabaseHelper(SplashActivity.this);
    database = dbHelper.getWritableDatabase();
    Log.i("testtt", "this line is working well...");
    openWelcomeActivity();
  }

  private void openWelcomeActivity() {

    Intent intent = new Intent(this, LogoActivity.class);
    startActivity(intent);
    this.finish();
  }

这是Logcat错误:
导致原因:安卓系统。未知错误(代码14 SQLITE_CANTOPEN):无法在android上打开数据库。database.sqlite。SQLiteConnection。nativeOpen(本地方法)
在Android 10+中创建数据库或写入外部存储有什么变化吗?

mrfwxfqh

mrfwxfqh1#

您不应该为Android 10+请求WRITE_EXTERNAL_STORAGE;它没有效果。
在文件中:
注意:如果您的应用面向Build.VERSION_CODES.R或更高版本,则此权限无效。
因此,您需要继续操作,而无需请求Android 10+的权限

private void askUserForPermission() {
    if (SDK_INT < Build.VERSION_CODES.Q)
        ActivityCompat.requestPermissions(this, new String[]
                                    {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
    else
        createAppDir();
}

请注意,您正在使用已弃用的API请求权限,请选中this question以获取替代API
另外,考虑CommonsWare指出的有价值的评论

更新日期:

Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error
(code 14 SQLITE_CANTOPEN): Could not open database at
android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)

正如CommonsWare在这篇评论中指出的,开发者不允许在Android 11+的外部存储器上的任意位置进行写入,因此引发了这个例外。

要解决此问题,开发人员需要:

1.允许用户通过使用ACTION_CREATE_DOCUMENT intentCheck here浏览外部/SD卡来选择特定文件夹,以了解更多详细信息。
1.或使用分配给应用程序的空间。
如果你想考虑第二种选择,可以不写共享的Environment.getExternalStorageDirectory().getAbsolutePath()目录,而是写SD卡getExternalFilesDir()或者写getFilesDir()的内部设备存储,这两个都分配给你的app,其他app都无法正常访问。
因此,您必须更改以下代码:

public static String SDCARD = Environment
                        .getExternalStorageDirectory().getAbsolutePath();

变成这样:

public static String SDCARD = context.getFilesDir().getAbsolutePath(); 

// or

public static String SDCARD = context.getExternalFilesDir(null).getAbsolutePath();

我保留了SDCARD的原样;但这并不表示它是SD共享存储器。

相关问题