Search code examples
javaandroidandroid-asynctask

Can't get doInBackground to work in AsyncTask


I'm new to AsyncTask so apologies in advance if my problem is silly. Long story short, I have a method that handles some files and I want to run it in the background. My class is below and the problem is that the method works fine when called directly, but absolutely nothing happens when I'm trying to call it via doInBackground.

This works: AttachFilesFromFolder.attach(files);

And this doesn't: new AttachFilesFromFolder().execute(files);

The class in question:

public class AttachFilesFromFolder extends AsyncTask<File[], Void, Void> {
    @Override
    protected Void doInBackground(File[]... files) {
        try {
            attach(files[0]);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void attach(File[] files) throws InterruptedException {
        for (File file : files) {
            log("For loop started.");
            File targetLocation = new File(Environment.getDataDirectory() + "/data/org.p4.epo.android/" + file.getName());

            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream in = new FileInputStream(file);
                        OutputStream out = new FileOutputStream(targetLocation);

                        byte[] buf = new byte[1024];
                        int len;

                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }

                        buf = null;
                        in.close();
                        in = null;
                        out.close();
                        out = null;
                        log("Copied file " + targetLocation.toString() + " successfully.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        SdkManager.sharedInstance().addAttachment(targetLocation.toString(), file.getName(), AttachMode.asNewPage, 1, false);
                        log("Attached " + file.getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            log("Thread T1 started.");
            t1.start();
            t1.join();
            log("Thread T2 started.");
            t2.start();
            t2.join();
        }
    }
}

Solution

  • Solved by using executeOnExecutor. That worked.