Ayushi bhardwaj Ayushi bhardwaj - 1 year ago 98
Java Question

how to extend scope of some variable in anonymous inner class

I've an anonymous class :

filepath.putFile(userItemPhotoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
Toast.makeText(MainActivity.this, "Uploading finished ..", Toast.LENGTH_SHORT).show();

I want to extend the scope of downloadUri to its outer block.

I tried but I failed to do so.
Declaring a final variable in the outer block will not work because we can't initialize it again inside.

Answer Source

Here, I would recommend using a "Holder" class that will help with storing values. It's a very useful mechanism that allows you to access data. Personally, I don't think that having public scoped variables are a good idea.

So you could have a holder type object with getters/setters to hold :

public class HoldThis {

    private Uri downloadUri;

    public void setUri(Uri uri){
        this.downloadUri = uri;

    public Uri getUri(){
        return downloadUri;


You also have the option to do something like the following:

Outer class: final Uri []uri = new Uri[1]; and then you can modify this in the inner class by just doing uri[0] = taskSnapshot.getDownloadUrl();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download