Устройство Huawei не будет импортировать базу данных - PullRequest
0 голосов
/ 22 ноября 2018

У меня есть несколько разных телефонов, и я думаю, что этот импорт работает на всех них, кроме моего Huawei Mate 20 Pro.Вот код -

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);
    }

В MainActivity фактическая загрузка составляет -

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();
    }

LogCat, который я получаю, когда запускаю это на моем Huawei, - -

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

Я подумал, что, возможно, у Huawei странная файловая структура или что-то в этом роде, но при поиске файла нет ошибок, он просто не читает информацию из него, как это делают другие.

Если это имеет значениеУстройство Huawei Mate 20 Pro работает под управлением Android 9.0.

Есть идеи?

** РЕДАКТИРОВАТЬ ** Если я использую Huawei, установите в приложении несколько вещей, которые затем следует сохранить вбазу данных, только для того, чтобы ее можно было экспортировать (я новичок во всем этом, и это казалось простым способом позволить мне экспортировать и импортировать). Затем я экспортирую и пытаюсь импортировать это на моем устройстве Android One, это не работает.

На самом деле я загрузил экспортированную БД, и она выглядит довольно пустой.Это наводит меня на мысль, что проблема в том, что Huawei использует другое внутреннее хранилище, и проблема в том, что, возможно, он никогда не сохраняет базу данных локально, поэтому не может ее экспортировать.

EDIT2 Все выглядит такбыть в порядке при чтении и записи базы данных внутри.Как я могу проверить правильность этой строки -

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

Если у меня нет root?Могу ли я использовать ADB для отслеживания и проверки, где Huawei хранит данные приложения?

1 Ответ

0 голосов
/ 22 ноября 2018

EDIT2 Все выглядит нормально при чтении и записи базы данных внутри.Как проверить правильность этой строки -

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

Не , а используйте the_context.getDatabasePath("Vehicles").getPath();, где the_context - это контекст.

Кроме того, если есть или не было других баз данных, и вы просто проверяете, существует ли файл базы данных, папка базы данных не будет существовать.Поэтому я бы посоветовал проверить, существует ли каталог database , проверив родительский путь, чтобы узнать, существует ли он, и если он не использует mkdirs для создания каталога (ов).

Вот выдержка, которая использует оба выше

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;
}
...