SoFunction
Updated on 2025-03-11

Android programming method to implement SD card to read database

This article describes the method of Android programming to implement SD card to read databases. Share it for your reference, as follows:

First add permissions in Manifest:

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

Then add the method in mainActivity:

SQLiteDatabase db;
private final String DATABASE_PATH = 
 .getExternalStorageDirectory().getAbsolutePath() + "/vote";
private String DATABASE_FILENAME = "db_vote.db";
// Initialize the databaseprivate SQLiteDatabase openDatabase() {
  try {
   String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
   File dir = new File(DATABASE_PATH);
   if (!())
    ();
   if (!(new File(databaseFilename)).exists()) {
    InputStream is = getResources().openRawResource(.db_vote);
    FileOutputStream fos = new FileOutputStream(databaseFilename);
    byte[] buffer = new byte[8192];
    int count = 0;
    while ((count = (buffer)) &gt; 0) {
     (buffer, 0, count);
    }
    ();
    ();
   }
   db = (databaseFilename, null);
   return db;
  } catch (Exception e) {
   ();
  }
  return null;
}

I hope this article will be helpful to everyone's Android programming design.