-1

I'm having a little trouble, im executing a method in my doinBackground task, so I'm getting a crash because im accesing to another class without finishing this method first, so i want to add a return or something to let the method know when it needs to launch the other activity. I have searched and I can't return a boolean, true or false into Firebase asynctask method. This is the method I use to download a file and replace it into internal memory, but when im doing this , the other activity I need to launch after this launches and i get a crash, so i need to first execute this download task and then if something is true launch my other activity

This is where I want to put a boolean or something that tells me that the download finished.

public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                Log.e("TamañoArchivo",""+taskSnapshot.getTotalByteCount());
                Log.e("NombreArchivo",""+xFile);

                try {
                    FileOutputStream fos = context.openFileOutput("pictos.txt", Context.MODE_PRIVATE);
                    fos.write(getStringFromFile(xFile.getAbsolutePath()).getBytes());
                    Log.e("xFILEDESCARGARPAIS",""+getStringFromFile(xFile.getAbsolutePath()));
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

The method is not an asyncTask, is an async but from Firebase, this is the method:

public boolean DescargarArchivosPais(String locale){

        File rootPath = new File(context.getCacheDir(),"MY_FILES");
        if(!rootPath.exists()) {
            rootPath.mkdirs();//si no existe el directorio lo creamos
        }

        StorageReference mStorageRef2 = FirebaseStorage.getInstance().getReference().child("Files/y/" + "y_" + locale + "." + "txt");
        StorageReference mStorageRef1 = FirebaseStorage.getInstance().getReference().child("Files/x/" + "x_" + locale + "." + "txt");
        Log.e("REFERENCIAx",""+ mStorageRef1);
        Log.e("REFERENCIAy",""+ mStorageRef2);

        final File xFile = new File(rootPath, "x.txt");
        final File yFile = new File(rootPath, "y.txt");

        mStorageRef1.getFile(xFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                Log.e("TamañoArchivo",""+taskSnapshot.getTotalByteCount());
                Log.e("NombreArchivo",""+xFile);

                try {

                    FileOutputStream fos = context.openFileOutput("x.txt", Context.MODE_PRIVATE);
                    fos.write(getStringFromFile(xFile.getAbsolutePath()).getBytes());
                    Log.e("LOG",""+getStringFromFile(xFile.getAbsolutePath()));
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

            }
        });

        mStorageRef2.getFile(yFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                Log.e("TamañoArchivo",""+taskSnapshot.getTotalByteCount());
                Log.e("NombreArchivo",""+yFile);

                try {
                    FileOutputStream fos = context.openFileOutput("y.txt", Context.MODE_PRIVATE);
                    fos.write(getStringFromFile(gruposFile.getAbsolutePath()).getBytes());
                    Log.e("LOG2",""+getStringFromFile(gruposFile.getAbsolutePath()));
                    fos.close();
                    fSuccess = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("printStackTrace",""+e.toString());
                    fSuccess = false;
                }
                fSuccess = true;
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                fSuccess=false;
                Log.e("printStackTrace",""+e.toString());
            }

        });
        return fSuccess;
    }
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77

2 Answers2

2

Updated with following comment (replace Activity reference and introduce interface instead):

You can definitively do things like that with AsyncTask. Please have a look at the following minimalist code:

public class MyTask extends AsyncTask<Void, Void, Boolean> {

    private IMyCallbackContext context;

    public MyTask(IMyCallbackContext context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        // Here you are still on the MainThread
        // Do Stuff
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // Here you are not on the MainThread
        // Do Stuff    
        return isSuccess;
    }

    @Override
    protected void onPostExecute(Boolean isSuccess) {
        // Here you are again on the MainThread
        if (isSuccess) {
            context.onTaskSuccessDoStuff();
        } else {
            context.onTaskFailureDoStuff();
        }
    }
}

public interface IMyCallbackContext {
    void onTaskSuccessDoStuff();
    void onTaskFailureDoStuff();
}

public class MyActivity extends Activity implements IMyCallbackContext {

    private void launchTask() {
        MyTask myTask = new MyTask(this);
        myTask.execute();
    }

    public void onTaskSuccessDoStuff() {
        // Do stuff after the task has completed
    }

    public void onTaskFailureDoStuff() {
        // Do stuff after the task has failed
    }
}

Edit: sorry I thought you had an AsyncTask

AdricoM
  • 579
  • 4
  • 11
  • 2
    Upvote for the answer. But never use the Activity reference directly. It might cause memory leaks. Instead create an Interface and pass the interface object to prevent leakage of Context object. – Mohammed Atif Jan 11 '18 at 18:12
  • Thank you for pointing that! I will update my post (and my habits) accordingly! – AdricoM Jan 11 '18 at 20:01
1

onSuccess() method has an asynchronous behaviour. This means that in order to use the data that you are getting from Firebase Storage, you need to wait for it. So to do that, there is no need to use an AsyncTask, you can simply create your own custom callback.

To make this happen, please see the last part for my answer from this post. As Mohammed Atif mentioned in his comment, never use the Activity reference directly because it will cause memory leaks. So the way I mentioned above, is the simplest and safest way in which you can achieve this.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193