d.mc2
d.mc2

Reputation: 1129

Getting objects out of an inner class/listener

I finally managed to get an object out of an AsyncTask (DogAsyncTask) with an interface/listener (DogListener):

public String fout(String url) {

    Dog d_in = new Dog("DogName");
    DogAsyncTask task = new DogAsyncTask(d_in);

    final String out = "";    <---Have tried but error for out becomes "The final local variable out cannot be assigned, since it is defined in an enclosing type"
    task.setDogListener(new DogListener()
    {
        @SuppressWarnings("unchecked")
        @Override
        public void DogSuccessfully(String data) {  <---The string I want to get
            Log.e("DogListened", data);
            out = data;
        }

        @Override
        public void DogFailed() {}
    });

    task.execute(url);
    return out;
}

My main activity calls this function (fout) and is supposed to get a String out of it. String data is already there and Log.e("DogListened", data); records it too. How can I return that outwards to my main activity? I have tried setting out = data and made out a final String on the outside but the "final local variable out cannot be assigned, since it is defined in an enclosing type" error comes up. How can I get around this?

Thanks

Upvotes: 2

Views: 676

Answers (2)

Orkun
Orkun

Reputation: 7238

I guess you cannot access to out because it is out of the listener's scope. You can maybe pass your out as a reference parameter to the constructor of your DogListener.

final String out = "";    
task.setDogListener(new DogListener( **out** )
{
    @SuppressWarnings("unchecked")
    @Override
    public void DogSuccessfully(String data) {  
        Log.e("DogListened", data);
        out = data;
    }

    @Override
    public void DogFailed() {}
});

BUT honestly I donT know how to pass parameters as a reference in Java like in C#..

EDIT:

This can help you too: Can I pass parameters by reference in Java?

Upvotes: 1

Stefan
Stefan

Reputation: 4705

Use a value holder, which basically is an object which stores some value in a field. The value holder can be assigned as final, but you can change the value. Follow the link for more info on this pattern: http://martinfowler.com/eaaCatalog/lazyLoad.html

However you can use your string as value holder: Just append to the empty string assigned to out. Or better use a StringBuffer object.

Upvotes: 0

Related Questions