0
votes

This is my scenario. I've got a POJO class, let's call it Car, declared like this:

public class Plan{
private String id;
private String userId;
private List< String > pictures;
}

In that class, the List< String > pictures is supposed to have the links to the Firebase Storage where I actually upload the pictures. I'm having problems doing this due to the async root of Firebase functions. In the first moment, that pictures list has the LOCAL PATH to the images, because I don't want the user to upload ANYTHING until he completes all the steps required to add a record to Firebase Database. So, I just save the local path of the images. But, once data is saved to the cloud, of course I'll need to actually upload those images to Firebase Storage and update the corresponding fields in the Firebase Database.

I'm stuck trying to do something like this:

    public void saveToDB(){

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference databaseReference = database.getReference().child( "cars" );
    databaseReference.push().setValue( this, new DatabaseReference.CompletionListener(){
        @Override
        public void onComplete( @Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference ){
            if( databaseError != null ){
                for( String imagePath : pictures ){
                    final DatabaseReference picReference = FirebaseDatabase.getInstance().getReference()
                            .child( "cars" )
                            .child( databaseReference.getKey() )
                            .child( "pictures" );

                    storageReference.putFile( Uri.fromFile( new File( imagePath ) ) )
                            .addOnSuccessListener( new OnSuccessListener< UploadTask.TaskSnapshot >(){
                                @Override
                                public void onSuccess( UploadTask.TaskSnapshot taskSnapshot ){
                                            picReference.child( "0" )
                                            .setValue( taskSnapshot.getMetadata().getPath() );
                                }
                            } );
                }
            }
        }
    } );
}

How should I do that so that all pictures get uploaded and all fields updated in the Firebase Database?

1

1 Answers

0
votes

You'll likely end up collecting all the Task objects returned by putFile() into a List, then pass that to Tasks.whenAll() to get another Task that indicates when all the uploads are done. You can get the URLs from all those successful tasks to populate the database. It'll be a non-trivial amount of code to arrange all this, and you should definitely be familiar with the Play services task api to do this well.