3

I have a few different phones and I think this import works on them all, except my Huawei Mate 20 Pro. Here is the code -

public static void importDB() {
    Log.i("ImportDB", "Started");
    try {
        String DB_PATH = "/data/data/com.androidandyuk.autobuddy/databases/Vehicles";

        File sdcard = Environment.getExternalStorageDirectory();
        String yourDbFileNamePresentInSDCard = sdcard.getAbsolutePath() + File.separator + "AutoBuddy/Vehicles.db";

        Log.i("ImportDB", "SDCard File " + yourDbFileNamePresentInSDCard);

        File file = new File(yourDbFileNamePresentInSDCard);
        // Open your local db as the input stream
        InputStream myInput = new FileInputStream(file);

        // Path to created empty db
        String outFileName = DB_PATH;

        // Opened assets database structure
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    } catch (Exception e) {
        Log.i("ImportDB", "Exception Caught" + e);
    }
    loadBikes();
    Fuelling.loadFuels();
    Maintenance.loadLogs();
    ToDo.loadToDos();
    Context context = App.getContext();
    Toast.makeText(context, "Data Imported. Close app and reopen", Toast.LENGTH_LONG).show();
    if (bikes.size() > 0) {
        activeBike = 0;
    }
}

public void importDB2() {

        Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/AutoBuddy/");
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setDataAndType(selectedUri, "*/*");
        Intent i = Intent.createChooser(intent, "File");
        startActivityForResult(i, CHOOSE_FILE_REQUESTCODE);
    }


@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch(requestCode){
            case CHOOSE_FILE_REQUESTCODE:
                if(resultCode==-1){
                    Uri uri = data.getData();
                    String yourDbFileNamePresentInSDCard = uri.getPath();

                    //int index = yourDbFileNamePresentInSDCard.indexOf(":");
                    //if(index > 0) {
                    //    yourDbFileNamePresentInSDCard = yourDbFileNamePresentInSDCard.substring(index+1);
                    //}

                    Log.i("ImportDB", "Started");
                    try {
                        String DB_PATH = "/data/data/com.androidandyuk.autobuddy/databases/sessions";

//                        File sdcard = Environment.getExternalStorageDirectory();
//                        yourDbFileNamePresentInSDCard = sdcard.getAbsolutePath() + File.separator + "LapTimerBuddy/LapTimer.db";

                        Log.i("ImportDB", "SDCard File " + yourDbFileNamePresentInSDCard);

                        File file = new File(yourDbFileNamePresentInSDCard);
                        // Open your local db as the input stream
                        InputStream myInput = new FileInputStream(file);

                        // Path to created empty db
                        String outFileName = DB_PATH;

                        // Opened assets database structure
                        OutputStream myOutput = new FileOutputStream(outFileName);

                        // transfer bytes from the inputfile to the outputfile
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = myInput.read(buffer)) > 0) {
                            myOutput.write(buffer, 0, length);
                        }

                        // Close the streams
                        myOutput.flush();
                        myOutput.close();
                        myInput.close();
                    } catch (Exception e) {
                        Log.i("ImportDB", "Exception Caught" + e);
                    }
                    loadBikes();
                    Fuelling.loadFuels();
                    Maintenance.loadLogs();
                    ToDo.loadToDos();
                    Context context = App.getContext();
                    Toast.makeText(context, "Data Imported. Close app and reopen", Toast.LENGTH_LONG).show();
                    if (bikes.size() > 0) {
                        activeBike = 0;
                    }
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

In MainActivity, the actual load is -

public static void loadBikes() {

        Log.i("Main Activity", "New Bikes Loading");
        int bikesSize = sharedPreferences.getInt("bikesSize", 0);

        Log.i("Bikes Size", "" + bikesSize);
        bikes.clear();

        try {

            Cursor c = vehiclesDB.rawQuery("SELECT * FROM vehicles", null);

            int makeIndex = c.getColumnIndex("make");
            int modelIndex = c.getColumnIndex("model");
            int regIndex = c.getColumnIndex("reg");
            int bikeIdIndex = c.getColumnIndex("bikeId");
            int VINIndex = c.getColumnIndex("VIN");
            int serviceDueIndex = c.getColumnIndex("serviceDue");
            int MOTdueIndex = c.getColumnIndex("MOTdue");
            int lastKnownServiceIndex = c.getColumnIndex("lastKnownService");
            int lastKnownMOTIndex = c.getColumnIndex("lastKnownMOT");
            int yearOfManIndex = c.getColumnIndex("yearOfMan");
            int notesIndex = c.getColumnIndex("notes");
            int estMileageIndex = c.getColumnIndex("estMileage");
            int MOTwarnedIndex = c.getColumnIndex("MOTwarned");
            int serviceWarnedIndex = c.getColumnIndex("serviceWarned");
            int taxDueIndex = c.getColumnIndex("taxDue");

            c.moveToFirst();

            do {

                ArrayList<String> make = new ArrayList<>();
                ArrayList<String> model = new ArrayList<>();
                ArrayList<String> reg = new ArrayList<>();
                ArrayList<String> bikeId = new ArrayList<>();
                ArrayList<String> VIN = new ArrayList<>();
                ArrayList<String> serviceDue = new ArrayList<>();
                ArrayList<String> MOTdue = new ArrayList<>();
                ArrayList<String> lastKnownService = new ArrayList<>();
                ArrayList<String> lastKnownMOT = new ArrayList<>();
                ArrayList<String> yearOfMan = new ArrayList<>();
                ArrayList<String> notes = new ArrayList<>();
                ArrayList<String> estMileage = new ArrayList<>();
                ArrayList<String> MOTwarned = new ArrayList<>();
                ArrayList<String> serviceWarned = new ArrayList<>();
                ArrayList<String> taxDue = new ArrayList<>();

                try {

                    make = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(makeIndex));
                    model = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(modelIndex));
                    reg = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(regIndex));
                    bikeId = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(bikeIdIndex));
                    VIN = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(VINIndex));
                    serviceDue = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(serviceDueIndex));
                    MOTdue = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(MOTdueIndex));
                    lastKnownService = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(lastKnownServiceIndex));
                    lastKnownMOT = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(lastKnownMOTIndex));
                    yearOfMan = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(yearOfManIndex));
                    notes = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(notesIndex));
                    estMileage = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(estMileageIndex));
                    MOTwarned = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(MOTwarnedIndex));
                    serviceWarned = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(serviceWarnedIndex));
                    taxDue = (ArrayList<String>) ObjectSerializer.deserialize(c.getString(taxDueIndex));

                    Log.i("Bikes Restored ", "Count :" + make.size());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("Loading Bikes", "Failed attempt");
                }

                Log.i("Retrieved info", "Log count :" + make.size());
                if (make.size() > 0 && model.size() > 0 && bikeId.size() > 0) {
                    // we've checked there is some info
                    if (make.size() == model.size() && model.size() == bikeId.size()) {
                        // we've checked each item has the same amount of info, nothing is missing
                        for (int x = 0; x < make.size(); x++) {
                            int thisId = Integer.parseInt(bikeId.get(x));
                            double thisEstMileage = Double.parseDouble(estMileage.get(x));
                            boolean thisMOTwarned = Boolean.parseBoolean(MOTwarned.get(x));
                            boolean thisServiceWarned = Boolean.parseBoolean(serviceWarned.get(x));
                            Bike newBike = new Bike(thisId, make.get(x), model.get(x), reg.get(x), VIN.get(x), serviceDue.get(x), MOTdue.get(x), lastKnownService.get(x), lastKnownMOT.get(x),
                                    yearOfMan.get(x), notes.get(x), thisEstMileage, thisMOTwarned, thisServiceWarned, taxDue.get(x));
                            Log.i("Adding", " " + x + " " + newBike);
                            bikes.add(newBike);
                        }
                    }
                }
            } while (c.moveToNext());

        } catch (Exception e) {

            Log.i("LoadingDB", "Caught Error");
            e.printStackTrace();

        }
        Bike.bikeCount = sharedPreferences.getInt("bikeCount", 0);
        loadLogs();
        loadFuels();
    }

The logcat I get when I run this on my Huawei is -

2018-11-22 09:43:07.358 13024-13024/com.androidandyuk.autobuddy I/ViewRootImpl: jank_removeInvalidNode all the node in jank list is out of time
2018-11-22 09:43:07.362 13024-13024/com.androidandyuk.autobuddy V/AudioManager: playSoundEffect   effectType: 0
2018-11-22 09:43:07.362 13024-13024/com.androidandyuk.autobuddy V/AudioManager: querySoundEffectsEnabled...
2018-11-22 09:43:07.363 13024-13024/com.androidandyuk.autobuddy I/ImportDB: Started
2018-11-22 09:43:07.364 13024-13024/com.androidandyuk.autobuddy I/ImportDB: SDCard File /storage/emulated/0/AutoBuddy/Vehicles.db
2018-11-22 09:43:07.366 13024-13024/com.androidandyuk.autobuddy I/Main Activity: New Bikes Loading
2018-11-22 09:43:07.366 13024-13024/com.androidandyuk.autobuddy I/Bikes Size: 0
2018-11-22 09:43:07.378 13024-13024/com.androidandyuk.autobuddy I/Bikes Restored: Count :0
2018-11-22 09:43:07.378 13024-13024/com.androidandyuk.autobuddy I/Retrieved info: Log count :0
2018-11-22 09:43:07.397 13024-13024/com.androidandyuk.autobuddy D/HwAppInnerBoostImpl: asyncReportData com.androidandyuk.autobuddy,2,1,1,0 interval=159
2018-11-22 09:43:07.469 13024-13024/com.androidandyuk.autobuddy D/HwAppInnerBoostImpl: asyncReportData com.androidandyuk.autobuddy,2,2,1,6 interval=231
2018-11-22 09:43:07.472 13024-13089/com.androidandyuk.autobuddy D/OpenGLRenderer:   HWUI Binary is  enabled

    --------- beginning of system
2018-11-22 09:43:07.485 13024-13089/com.androidandyuk.autobuddy D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2018-11-22 09:43:07.485 13024-13089/com.androidandyuk.autobuddy D/OpenGLRenderer:   HWUI Binary is  enabled
2018-11-22 09:43:07.654 13024-13024/com.androidandyuk.autobuddy D/HwAppInnerBoostImpl: asyncReportData com.androidandyuk.autobuddy,2,1,2,0 interval=416
2018-11-22 09:43:10.914 13024-13089/com.androidandyuk.autobuddy W/libEGL: EGLNativeWindowType 0x76f41cf010 disconnect failed
2018-11-22 09:43:10.928 1235-2380/? W/NotificationService: Toast already killed. pkg=com.androidandyuk.autobuddy callback=android.app.ITransientNotification$Stub$Proxy@2031e32
2018-11-22 09:43:15.404 1235-1659/? D/hw_netstat: total/5999/1982,com.google.android.keep/1891/1686,com.google.uid.shared:10015/2250/52,unknown:0/1570/0,com.android.vending/208/192,com.androidandyuk.autobuddy/80/52
2018-11-22 09:43:30.423 1235-1659/? D/hw_netstat: total/3866/1426,unknown:0/2252/80,com.google.uid.shared:10015/999/413,com.whatsapp/40/457,unknown:1051/341/67,com.huawei.appmarket/182/222,com.teslacoilsw.launcher/0/135,com.androidandyuk.autobuddy/52/52

I thought maybe Huawei have a weird file structure or something, but there are no errors about not finding the file, it just doesn't read the info from it like others do.

If it matters the device is a Huawei Mate 20 Pro running Android 9.0.

Any ideas?

**EDIT ** If I use the Huawei, set a few things in the app, which then should save to a database, only so it can be exported (I'm, new to all this and this seemed an easy way to let me export and import) I then export and try and import that on my Android One device, it doesn't work.

In fact, I've uploaded the exported DB and it looks to be rather empty. This leads me to believe the issue is with Huawei using different internal storage and the problem is perhaps it never saves the database locally, so it can't export it.

EDIT2 Everything looks to be okay when reading and writing the database internally. How can I check this line is correct -

String DB_PATH = "/data/data/com.androidandyuk.autobuddy/databases/Vehicles";

If I don't have root? Can I use ADB to snoop round and check that is where the Huawei stores the app data?

AndyCr15
  • 465
  • 5
  • 17

1 Answers1

2

EDIT2 Everything looks to be okay when reading and writing the database internally. How can I check this line is correct -

String DB_PATH = "/data/data/com.androidandyuk.autobuddy/databases/Vehicles";

Don't, rather use the_context.getDatabasePath("Vehicles").getPath(); where the_context is a context.

Additionally if there are or have been no other databases and you are just checking that the database file exists then the databases folder won't exist. As such, I'd suggest checking to see if the databases directory exists by checking the path's parent to see if it exists and if not using mkdirs to create the directory(ies).

Here's an extract that uses both the above

mDBPath = context.getDatabasePath(database).getPath();
if (!ifDatabaseExists(mDBPath)) {
    ...... copy the db from the assets folder
}


private boolean ifDatabaseExists(String dbpath) {
    File db = new File(dbpath);
    if(db.exists()) return true;
    File dir = new File(db.getParent());
    if (!dir.exists()) {
        dir.mkdirs();
    }
    return false;
}
MikeT
  • 51,415
  • 16
  • 49
  • 68