0

I make a chatting app with android studio. I want to create settings activity. I successfully load profile image to firebase storage. But when I retrieve profile image from storage it seems end of the onactivityresult. But when I go back to main activity the profile image is disappearing I want when I enter to settings activity profile image is retrieves. I try to do with picasso & glide but not working.

enter code here 

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.File;
import java.net.URI;
import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;

public class SettingsActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private CircleImageView set_profile_image;
    private EditText set_user_name , set_profile_status;
    private Button update_settings_button;
    private String CurrentUserID;
    private FirebaseAuth mAuth;
    private DatabaseReference RootRef;
    private static final int GalleryPick = 1;
    private StorageReference UserProfileImagesRef;
    private ProgressDialog loadingBar;

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

        mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
        setSupportActionBar(mToolbar);

        define();
        RetrieveUserInfo();
    }

    private void define() {
        set_profile_image = (CircleImageView) findViewById(R.id.set_profile_image);
        set_user_name = (EditText) findViewById(R.id.set_user_name);
        set_profile_status = (EditText) findViewById(R.id.set_profile_status);
        update_settings_button = (Button) findViewById(R.id.update_settings_button);
        mAuth = FirebaseAuth.getInstance();
        CurrentUserID = mAuth.getCurrentUser().getUid();
        RootRef = FirebaseDatabase.getInstance().getReference();
        UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
        loadingBar = new ProgressDialog(this);
    }

    public void set_profile_image_click(View view){
        Intent galleryIntent = new Intent();
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent , GalleryPick);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
            Uri ImageUri = data.getData();
            CropImage.activity()
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1 , 1)
                    .start(this);
        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK){
                loadingBar.setTitle("Set Profile Image");
                loadingBar.setMessage("Your Profile Image is Updating...");
                loadingBar.setCanceledOnTouchOutside(false);
                loadingBar.show();

                final Uri resultUri = result.getUri();

                StorageReference FilePath = UserProfileImagesRef.child(CurrentUserID + ".jpg");
                FilePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()){
                            Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully", Toast.LENGTH_SHORT).show();

                            final String downloadUrl = task.getResult().getUploadSessionUri().toString();

                            RootRef.child("Users").child(CurrentUserID).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()){
                                        Toast.makeText(SettingsActivity.this, "Image Uploaded Database Successfully", Toast.LENGTH_SHORT).show();
                                        loadingBar.dismiss();
                                    }
                                }
                            });
                        }else {
                            String message = task.getException().toString();
                            Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
                            loadingBar.dismiss();
                        }
                    }
                });
                Glide.with(SettingsActivity.this).load(new File(resultUri.getPath())).into(set_profile_image);
            }
        }
    }

    private void RetrieveUserInfo() {
        RootRef.child("Users").child(CurrentUserID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))){
                    String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
                    String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();
                    String RetrieveProfileImage = dataSnapshot.child("image").getValue().toString();

                    set_user_name.setText(RetrieveUserName);
                    set_profile_status.setText(RetrieveProfileStatus);

                    //Picasso.get().load(RetrieveProfileImage).into(set_profile_image);
                    Glide.with(SettingsActivity.this).load(new File(RetrieveProfileImage.)).into(set_profile_image);
                }
                else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
                    String RetrieveUserName = dataSnapshot.child("name").getValue().toString();
                    String RetrieveProfileStatus = dataSnapshot.child("status").getValue().toString();

                    set_user_name.setText(RetrieveUserName);
                    set_profile_status.setText(RetrieveProfileStatus);
                }
                else{
                    //set_user_name.setVisibility(View.VISIBLE);
                    Toast.makeText(SettingsActivity.this, "Please update your profile Settings", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    public void update_settings_button_click(View view){
        UpdateSettings();
    }

    private void UpdateSettings() {
        String setUserName = set_user_name.getText().toString();
        String setProfileStatus = set_profile_status.getText().toString();

        if (TextUtils.isEmpty(setUserName)){
            Toast.makeText(this, "Please write your User Name", Toast.LENGTH_SHORT).show();
        }
        if (TextUtils.isEmpty(setProfileStatus)){
            Toast.makeText(this, "Please write your Status", Toast.LENGTH_SHORT).show();
        }
        else {
            HashMap<String , String> ProfileMap = new HashMap<>();
                ProfileMap.put("uid" , CurrentUserID);
                ProfileMap.put("name" , setUserName);
                ProfileMap.put("status" , setProfileStatus);
            RootRef.child("Users").child(CurrentUserID).setValue(ProfileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()){
                        SendUserToMainActivity();
                        Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
                    }else {
                        String message = task.getException().toString();
                        Toast.makeText(SettingsActivity.this, "Error: " + message , Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
  
    private void SendUserToMainActivity() {
        Intent mainIntent = new Intent(SettingsActivity.this , MainActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mainIntent);
        finish();
    }
}
  • This code `final String downloadUrl = task.getResult().getUploadSessionUri().toString();` does **not** return the download URL for the image, but its (completely unrelated) upload session URI. To get the download URL, follow the code in the documentation on [getting a download URL](https://firebase.google.com/docs/storage/android/download-files#download_data_via_url) or as shown in [this answer](https://stackoverflow.com/questions/51056397/how-to-use-getdownloadurl-in-recent-versions). – Frank van Puffelen Jul 11 '20 at 03:04
  • I try this but doesn't work. What can I do – DSS company Jul 11 '20 at 18:56
  • Update your question to show the updated code. I'd also highly recommend isolating the problem, as there's quite a bit of code in your question right now. – Frank van Puffelen Jul 11 '20 at 19:08

0 Answers0