Search code examples
androiddatabasesqlitewear-osandroid-wear-data-api

What is the best way to send whole .db file from android wear to smartphone?


Now I am making an wear app that records accelerator, magnet-field, gyroscope (50Hz) and write them to a .db file (that contains 3 tables(acceleration, magnet-field, gyroscope) using SQLiteOpenHelper.

Once a day, I would like to send the .db file to its handheld.

I think it is the best to use DataApi and I tried to replace Realm by SQLite in this code(https://gist.github.com/tajchert/dc30560891bc6aee76fb).

In this code, I thought this part

public static void syncRealm(Context context){
        File writableFolder = context.getFilesDir();
        File realmFile = new File(writableFolder, Realm.DEFAULT_REALM_NAME);
        Asset realAsset = Tools.assetFromFile(realmFile);
        new FileSender(realAsset, context).execute();
}

should be changed like this

 public static void syncDB(Context context) {
    WearSqliteOpenHelper helper = new WearSqliteOpenHelper(context);
    String dbPath = helper.getReadableDatabase().getPath();
    File dbFile = new File(dbPath);
    Uri dbUri = Uri.fromFile(dbFile);
    Asset realAsset = Asset.createFromUri(dbUri);
    new FileSender(realAsset, context).execute();
  }

but I don't know how to convert (byte [] byteArray) to .db file in handheld. (What is the alternative function of "toFile" below. this code is also in https://gist.github.com/tajchert/dc30560891bc6aee76fb)

   private void toFile(byte [] byteArray){
        File writableFolder = ListenerService.this.getFilesDir();
        File realmFile = new File(writableFolder, Realm.DEFAULT_REALM_NAME);
        if (realmFile.exists()) {
            realmFile.delete();
        }
        try {
            FileOutputStream fos=new FileOutputStream(realmFile.getPath());
            fos.write(byteArray);
            fos.close();
        }
        catch (java.io.IOException e) {
            Log.d(TAG, "toFile exception: " + e.getLocalizedMessage());
        }
    }

Please help me!!!


Solution

  • Basically, the steps to do this are as follows:

    1. Access the raw DB file on the handheld (your original question had this part right)
    2. Read that file into a byte array (Elegant way to read file into byte[] array in Java, among others)
    3. Send the ByteArray to Wear using the Data API (probably as an asset: http://developer.android.com/training/wearables/data-layer/assets.html)
    4. Save that ByteArray back into the DB path on Wear (lots of examples of this online, here's one: http://www.java2s.com/Code/Java/File-Input-Output/Readfiletobytearrayandsavebytearraytofile.htm)

    There's no need to deal with intermediate files.