question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

CopyTask function copies empty file from usb to internal storage.

See original GitHub issue

This is the function from where file is copied

UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(getActivityContext() /* Context or Activity */);
        for (UsbMassStorageDevice device : devices) {

            // before interacting with a device you need to call init()!
            //considering only one device is inserted in every case
            try {
                device.init();
                // Only uses the first partition on the device
                FileSystem currentFs = device.getPartitions().get(0).getFileSystem();
                UsbFile folder = currentFs.getRootDirectory().search(sBackupFolder).search(folderName);
                if (folder == null) {
                    Utilities.Toaster(getActivityContext(), "Backup folder not found");
                } else {
                    Utilities.Toaster(getActivityContext(), "Backup folder found. Checking for files");
                    folder.listFiles();
                    int fileCount = 0;
                    List<String> list = new ArrayList<>();
                    if (folder.list() != null) {
                        for (int i = 0; i < folder.listFiles().length; i++) {
                            UsbFile backupFile = folder.listFiles()[i];
                            if (backupFile.getName().equals("DB1V" + DaoMaster.SCHEMA_VERSION + "Backup.db") || backupFile.getName().equals("DB2V" + 3 + "Backup.db")) {
                                fileCount++;
                            }
                        }
                        if (fileCount < 2)
                            Utilities.Toaster(getActivityContext(), "Backup files missing");
                        else {
                            //todo copy db to desired location
                            Utilities.Toaster(getActivityContext(), "Backup files found");
                            for (int i = 0; i < folder.listFiles().length; i++) {
                                UsbFile backupFile = folder.listFiles()[i];
                                if (backupFile.getName().equals("DB1V" + DaoMaster.SCHEMA_VERSION + "Backup.db")) {
                                    //copy greenDB to app folder
                                    CopyTaskParam sourceDestination = new CopyTaskParam();
//                                    File dbFile = new File(getActivityContext().getDatabasePath("green-db").getPath());
                                    File dbFile = new File(Environment.getExternalStorageDirectory()+"/green.db");
                                    sourceDestination.from = backupFile;
                                    sourceDestination.to = dbFile;

                                    new CopyTask(getActivityContext()).execute(sourceDestination);

                                }
                              /*  if (backupFile.getName().equals("DB2V" + 3 + "Backup.db")) {
                                    //copy sugarDB to app folder
                                    CopyTaskParam sourceDestination = new CopyTaskParam();
                                    File dbFile = new File(getActivityContext().getDatabasePath("syntech_tabletbanking.db").getPath());
                                    sourceDestination.from = backupFile;
                                    sourceDestination.to = dbFile;
                                    new CopyTask(getActivityContext()).execute(sourceDestination);
                                }*/
                            }
                        }

                    } else {
                        Utilities.Toaster(getActivityContext(), "Backup files missing");
                    }
                    setupRecyclerView(list);
                }
                device.close();
            } catch (IOException | NullPointerException e) {
                e.printStackTrace();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivityContext(), "Restore failed " + e.toString(), Toast.LENGTH_SHORT).show();
                        unregisterReceiver(mUsbReceiver);
                        dialog.dismiss();
                    }
                }, 3000);
            }
        }

This is the file I created from your reference.

public class CopyTask extends AsyncTask<CopyTaskParam, Integer, Void> {

    private ProgressDialog dialog;
    private CopyTaskParam param;
    private Context context;

    public CopyTask(Context context) {
        this.context = context;
        dialog = new ProgressDialog(context);
        dialog.setTitle("Copying file");
        dialog.setMessage("Copying a file to the internal storage, this can take some time!");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
    }

    @Override
    protected void onPreExecute() {
        dialog.show();
    }

    @Override
    protected Void doInBackground(CopyTaskParam... params) {
        long time = System.currentTimeMillis();
        param = params[0];
        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(param.to));

            Log.d("TAG", "Copy file with length: " + param.from.getLength());
            out.write(convertIntoBytes(param.from.getAbsolutePath()));
            out.close();
        } catch (IOException e) {
            Log.e("TAG", "error copying!", e);
        }
        Log.d("TAG", "copy time: " + (System.currentTimeMillis() - time));
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        dialog.dismiss();
        Utilities.Toaster(context, "Database Restored");
    }

    private byte[] convertIntoBytes(String db) {
        try {
            File dbFile = new File(db);
            FileInputStream fis = new FileInputStream(dbFile);
            // Transfer bytes from the input file to the output file
            byte[] bytesArray = new byte[(int) dbFile.length()];
            fis.read(bytesArray);
            fis.close();
            return bytesArray;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
magnusjacommented, Sep 2, 2019

Ok interesting. Then I will close this for now, reopen if you encounter this again.

0reactions
SynergySaugatcommented, Sep 2, 2019

currently i have solved the issue from a different approach… I converted the UsbFile into bytearray ani wrote it into internal storage so it works now… Thankyou for your feedback 😄 I read your thesis also… Had a great help from there too.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Copy File/Dir error to any External OTG/USB Device
Copy File /Dir error to any External OTG/USB Device ... since the Copy'ing is happening only between internal storage and the USB device...
Read more >
How to Copy Files from One Drive to Another Drive
Select the files you want to copy and then right-click and select Copy in the pop-up menu. You can also use the Ctrl...
Read more >
Gradle copy creates an empty file - Stack Overflow
This task copies files from pdo-shared */ task copyFromCommonProject(type:Copy, dependsOn: configurations.commonProjectContent){ from configurations.
Read more >
Problems may occur when you try to transfer files to or from a ...
Resolves a problem where a device that is connected to a USB 2.0 hub in Windows XP, Windows Vista, or Windows 7 may...
Read more >
How To: Copy file from USB to switch | Extreme Portal
By default the file from the USB or memory-card will be copied to the switch memory"/usr/local/cfg" and when executing the command, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found