Ad

How To Get Uri Value?

I have copied the value of the String photolink in another string PhotoLink1 but this show value only in URI method but not out side the Method, I don't how to get the value or is there anything I miss. Please tell me how to get this value or how should i make this code worked. I searched lot of questions about this but I can't get the solution .

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);
        Toolbar toolbar = (Toolbar)findViewById(R.id.setup_toolbar);
        setSupportActionBar(toolbar);
        firebaseAuth= FirebaseAuth.getInstance();
        firestore = FirebaseFirestore.getInstance();
        storageReference=FirebaseStorage.getInstance().getReference();
        getSupportActionBar().setTitle("Account Setup");
        circleImageView=(CircleImageView)findViewById(R.id.imageView);
        n=(EditText)findViewById(R.id.name_txt_up);
        s=(Button)findViewById(R.id.save_set_button);
        s.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String user = n.getText().toString().trim();
                if(!TextUtils.isEmpty(user) && imageURI!=null)
                {
                    String user_id= firebaseAuth.getCurrentUser().getUid();
                     StorageReference img_path = storageReference.child("profile_image").child(user_id+ ".jpg");
                    img_path.putFile(imageURI).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                            if(task.isSuccessful())
                            {
                                Task<Uri> task_uri = task.getResult().getMetadata().getReference().getDownloadUrl();
                                task_uri.addOnSuccessListener(new OnSuccessListener<Uri>() {
                                    @Override
                                    public void onSuccess(Uri uri) {
                                        String photoLink = uri.toString();
                                        getImageUri(photoLink);
                                        Toast.makeText(Setup_Activity.this, ""+photoLink, Toast.LENGTH_SHORT).show();
                                        Log.d("photLink", ""+PhotoLink1);
                                    }
                                });

                                Map<String,String > userMap= new HashMap<>();
                                userMap.put("name",user);
                                userMap.put("image", PhotoLink1);
                                firestore.collection("Users").document().set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful())
                                        {
                                            Toast.makeText(Setup_Activity.this, "This is  good", Toast.LENGTH_SHORT).show();
                                        }
                                        else
                                        {
                                            String err= task.getException().getMessage();
                                            Toast.makeText(Setup_Activity.this, "Error "+err, Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                            else
                            {
                                String err= task.getException().getMessage();
                                Toast.makeText(Setup_Activity.this, "Error "+err, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
                else
                {
                    Toast.makeText(Setup_Activity.this, "Empty Text Fields", Toast.LENGTH_SHORT).show();
                }
            }
        });
        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                {
                    if(ContextCompat.checkSelfPermission(Setup_Activity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
                    {
                        Toast.makeText(Setup_Activity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
                        ActivityCompat.requestPermissions(Setup_Activity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
                    }
                    else
                    {
                        getImage();


                    }
                }
                else
                {
                    getImage();
                }
            }
        });


    }

    private void getImageUri(String photoLink) {
        PhotoLink1 =photoLink;
    }

    public void getImage(){
        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .start(Setup_Activity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
               imageURI = result.getUri();
               circleImageView.setImageURI(imageURI);
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }
Ad

Answer

By the time you are trying to add those values to your userMap using the following lines of code:

Map<String,String > userMap = new HashMap<>();
userMap.put("name",user);
userMap.put("image", PhotoLink1);

The photoLink has not finished loading yet from the Firebase Storage and this is because the listener you have added to your task_uri object is being invoked some unknown amount of time later after your task finishes. You don't know how long it's going to take, it may take from a few hundred milliseconds to a few seconds before that photoLink is actually available. The onSuccess() method has an asynchronous behavior, that's why you cannot get that photoLink in such a way.

A quick solve for this problem would be to move all that block of code related to adding data to the userMap, inside the onSuccess() method. In this you are waiting for the callback and photoLink your will be available. Otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Ad
source: stackoverflow.com
Ad