简体   繁体   中英

How to keep sqlite database on an android device if the app is uninstalled?

My sqlite database is automatically deleted when my app is uninstalled. I wish to keep the database, so I don't need to rebuild the database when I reinstall the app.

By default, all databases of Android app are saved in /data/data/your-package-name/databases folder. When you uninstall the app, the /data/data/your-package-name directory and all of its subdirectory are deleted. You can't keep the database files if they are saved in this location.

But If you save your database files to SD card, the files are kept even after uninstall.

Here is an example of creating database is external directory

public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(final Context context) {
        super(context, Environment.getExternalStorageDirectory()
                + File.separator + FILE_DIR
                + File.separator + DATABASE_NAME, null, DATABASE_VERSION);
    ...

    }
    ...

}

This question is answered here How to store sqlite database directly on sdcard

Remember to add permission to write external storage in your manifest

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

Also I see that READ_EXTERNAL_STORAGE & WRITE_EXTERNAL_STORAGE are classified as 'Dangerous Permissions'

reff: https://developer.android.com/guide/topics/permissions/requesting.html

You'll need to get user permission AT RUNTIME (only once). This page describes how to do it: https://developer.android.com/training/permissions/requesting.html

Here is sample code (from Read and Write permission for storage and gallery usage for marshmallow ) that does this check

public class MainActivity extends AppCompatActivity implements 

ActivityCompat.OnRequestPermissionsResultCallback{

  private static final int REQUEST_WRITE_PERMISSION = 786;

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {            
        openFilePicker();
    }
  }

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

  private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
    } else {
        openFilePicker();
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM