0

I want to get the DownloadUrl from an image I uploaded to Firebase but when I try loading it later, I only get a not found exception:

public class ProfileActivity extends AppCompatActivity{

private static final int CHOOSE_IMAGE = 200;
//Initialize items
EditText inputUsername, inputBirthday;
FloatingActionButton mainaction;
FloatingActionButton homeaction;
FloatingActionButton profileaction;
StorageReference profileimageRef;
String profileimageurl;
Button actionSaveProfile;
FirebaseAuth mAuth;
ProgressBar progressBar;
ImageView profileimage;
Boolean isfabopen;
Uri uriProfileImage;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);


    isfabopen = false;
    mainaction = findViewById(R.id.fab_expand);
    homeaction = findViewById(R.id.fab_home);
    profileaction = findViewById(R.id.fab_profile);
    inputUsername = findViewById(R.id.input_username);
    inputBirthday = findViewById(R.id.input_birthday);
    actionSaveProfile = findViewById(R.id.action_save_profile);
    profileimage = findViewById(R.id.profile_image);
    progressBar = findViewById(R.id.progressbar);
    mAuth = FirebaseAuth.getInstance();

    //Expand, collapse menu
    mainaction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!isfabopen)
            {
                ShowFab();
            }else
            {
                CloseFab();
            }
        }
    });

    profileimage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showImageChooser();
        }
    });

    homeaction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(ProfileActivity.this, MainActivity.class));
        }
    });

    actionSaveProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveUserData(v);
        }
    });

    loadUserData();
}

private void loadUserData() {
    FirebaseUser user = mAuth.getCurrentUser();

    //If no profile picture found
    if(user.getPhotoUrl() != null)
    {
        String photoUrl = user.getPhotoUrl().toString();

        //Set profile picture
        Glide.with(this)
                .load(user.getPhotoUrl().toString())
                .into(profileimage);
    }

    //If no username found
    if(user.getDisplayName() != null)
    {
        String username = user.getDisplayName();

        //Insert display name
        inputUsername.setText(user.getDisplayName());
    }


}


private void saveUserData(View v)
{
    String name = inputUsername.getText().toString().trim();
    String birthtday = inputBirthday.getText().toString().trim();

    //Check if has content
    if(name.isEmpty())
    {
        Snackbar.make(v, R.string.message_username_empty, Snackbar.LENGTH_SHORT)
                .setAction("Action", null).show();
        inputUsername.requestFocus();

    }else if(birthtday.isEmpty()) {
        Snackbar.make(v, R.string.message_birthday_empty, Snackbar.LENGTH_SHORT)
                .setAction("Action", null).show();
        inputBirthday.requestFocus();
    }


    //Get user
    FirebaseUser user = mAuth.getCurrentUser();

    //Upload information
    if(user != null && profileimageurl != null)
    {
        UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
                .setDisplayName(name)
                .setPhotoUri(Uri.parse(profileimageurl))
                .build();

        Log.wtf("ImageURL3", profileimageurl);

        //Show progressbar
        progressBar.setVisibility(View.VISIBLE);

        user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                //Hide progressbar
                progressBar.setVisibility(View.GONE);

                if(task.isSuccessful())
                {
                    Toast.makeText(ProfileActivity.this, R.string.message_profile_updated, Toast.LENGTH_SHORT).show();
                }else
                {
                    Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


}


//When got activity result from showImageChooser
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //Check if result is ok
    if(requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data !=null && data.getData() != null)
    {
        //Save uri of image
        uriProfileImage = data.getData();

        try
        {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
            profileimage.setImageBitmap(bitmap);

            uploadToFirebase();
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

private void uploadToFirebase() {

    //Select destination filename, folder
    profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
    Log.wtf("ImageURL", profileimageRef.toString());

    //Upload image
    if(uriProfileImage != null)
    {
        //Show progressbar
        progressBar.setVisibility(View.VISIBLE);

        profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                //Hide progressbar
                progressBar.setVisibility(View.GONE);

                //Check if was successful
                if(task.isSuccessful())
                {
                    //Set profile image url
                    profileimageurl = task.getResult().toString();
                    Log.wtf("ImageURL2", profileimageurl);
                }else
                {
                    Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

}

private void showImageChooser()
{
    //Create chooser
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);

    //Start chooser activity and wait for result
    startActivityForResult(Intent.createChooser(intent, getString(R.string.label_profile_pic_chooser)), CHOOSE_IMAGE);
}

private void ShowFab() {
    //Bool for menu open
    isfabopen = true;

    //Set buttons visible
    homeaction.setVisibility(View.VISIBLE);
    profileaction.setVisibility(View.VISIBLE);

    //Rotate main button
    mainaction.animate().rotation(135f);

    //Expanding to top
    homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_100)).rotation(0f);
    profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_55)).rotation(0f);

}

private void CloseFab() {
    //Bool for menu closed
    isfabopen = false;

    //Hide buttons
    homeaction.setVisibility(View.VISIBLE);
    profileaction.setVisibility(View.VISIBLE);

    //Rotate main button
    mainaction.animate().rotation(0f);

    //Collapsing
    homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
    profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
}

//Check if user is logged in
@Override
protected void onStart() {
    super.onStart();

    //Check if user is already loggged in
    if(mAuth.getCurrentUser() == null)
    {
        finish();
        startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();

    //Go back to home activity
    finish();
    startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}

}

XML Code:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/colorPrimary"
        android:backgroundTint="@color/colorPrimary"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/profile_image"
            android:layout_width="156dp"
            android:layout_height="156dp"
            android:src="@drawable/camera_placeholder"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/relativeLayout2">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="@dimen/standard_23"
            android:paddingRight="@dimen/standard_23">

            <EditText
                android:id="@+id/input_username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorProfileAccent"
                android:hint="@string/label_username"
                android:inputType="textPersonName"
                android:paddingBottom="15dp"
                android:textColor="@color/colorProfileAccent"
                android:textColorHint="@color/colorProfileAccent" />

            <EditText
                android:id="@+id/input_birthday"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorProfileAccent"
                android:hint="@string/label_birthday"
                android:inputType="textPersonName"
                android:paddingBottom="15dp"
                android:textColor="@color/colorProfileAccent"
                android:textColorHint="@color/colorProfileAccent" />

            <Button
                android:id="@+id/action_save_profile"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="7dp"
                android:background="@drawable/rounded_btn_profile"
                android:text="@string/apply_changes"
                android:textColor="@color/colorProfileText" />

        </LinearLayout>

        <ProgressBar
            android:id="@+id/progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone" />

    </RelativeLayout>

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="wrap_content"
        android:layout_height="197dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab_home"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/standard_23"
            android:rotation="90"
            android:visibility="gone"
            app:fabSize="mini"
            app:srcCompat="@drawable/ic_home" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab_profile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/standard_23"
            android:rotation="0"
            android:translationY="@dimen/standard_55"
            android:visibility="gone"
            app:fabSize="mini"
            app:srcCompat="@drawable/ic_account_box" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab_expand"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:fabSize="normal"
            app:srcCompat="@drawable/ic_add" />
    </android.support.design.widget.CoordinatorLayout>


</android.support.constraint.ConstraintLayout>

I only get a java.io.FileNotFoundException: No such file or directory exception. Earlier I tried saving it with an Success-Listener as it's shown here: https://stackoverflow.com/a/50743192/6274419. But that also hadn't worked because the function doesn't exist in the newer Firebase version.

In general I want to display a profile picture and the username which are saved to Firebase and retrieved on next application startup.

Thanks in Advance!

Tim B.
  • 88
  • 2
  • 11
  • Are you saving and retrieving the image in the same activity ?? Please mention the code where these methods are called from and also the xml file. – Raj Jun 09 '18 at 19:57
  • @Raj Yes, I want to set a username and a profile picture in the activity which are retrieved when the activity is called. Posted the full file and XML now :) – Tim B. Jun 09 '18 at 21:07

2 Answers2

0

It takes some time to upload the image in firebase. So you can only retrieve the image when it is completely saved in database. Please call the loadUserData() method in OnSuccess and let me know if it works.

private void uploadToFirebase() {

        //Select destination filename, folder
        profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
        Log.wtf("ImageURL", profileimageRef.toString());

        //Upload image
        if(uriProfileImage != null)
        {
            //Show progressbar
            progressBar.setVisibility(View.VISIBLE);

            profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    //Hide progressbar
                    progressBar.setVisibility(View.GONE);

                    //Check if was successful
                    if(task.isSuccessful())
                    {
                        //Set profile image url
                        profileimageurl = task.getResult().toString();
                        loadUserData();

                        Log.wtf("ImageURL2", profileimageurl);
                    }else
                    {
                        Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
                    }

                }
            });
Raj
  • 2,997
  • 2
  • 12
  • 30
  • Unfortunately hadn't worked because as before I get the not found exception: There were 3 causes: java.io.FileNotFoundException(/com.google.firebase.storage.UploadTask$TaskSnapshot@d0eb287 (No such file or directory)). \n I think it's because of the URL I get a invalid URL for download but I don't know how to get another URL which is working. – Tim B. Jun 10 '18 at 06:21
  • Tried to get the content of the URL-string now: In the uploadToFirebase() void the profileimageRef = gs://appname-d21fc.appspot.com/profilepictures/1528611649724.jpg and the result of task.getResult().toString(); has the result com.google.firebase.storage.UploadTask$TaskSnapshot@9321862. But both variables didn't work for me. The first variable has the error: "No content provider" and the secend: "No such or file directory" as shown in the other comment – Tim B. Jun 10 '18 at 06:37
0

Solved it now by using another structure/method for retrieving the url with a UploadTask:

private void uploadToFirebase() {

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReference();

    //Select destination filename, folder
    final StorageReference profileimageRef = storageRef.child("profilepictures/" + System.currentTimeMillis() + ".jpg");
    UploadTask uploadTask = profileimageRef.putFile(uriProfileImage);

    Log.wtf("ImageURL", profileimageRef.toString());

    //Upload image
    if(uriProfileImage != null)
    {
        //Show progressbar
        progressBar.setVisibility(View.VISIBLE);

        Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful())
                {
                    throw task.getException();
                }

                return profileimageRef.getDownloadUrl();
            }

        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                progressBar.setVisibility(View.GONE);
                if(task.isSuccessful()) {
                    profileimageurl = task.getResult().toString();
                }
            }
        });
    }

}
Tim B.
  • 88
  • 2
  • 11