2

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

d.mc2
  • 1,129
  • 3
  • 16
  • 31
  • why do you have to declare the "out" as "final" ? – Orkun Jan 21 '12 at 10:47
  • it was just a try since others have said declare as a final to get it out of the inner class – d.mc2 Jan 21 '12 at 10:49
  • well.. then I d suggest you declare it without the final keyword and declare it in the scope of your activity. Then you can access and change its value from within. – Orkun Jan 21 '12 at 10:54
  • that's what I tried at first, however, it did not work out. Thanks a lot for your help though – d.mc2 Jan 21 '12 at 10:56

2 Answers2

1

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?

Community
  • 1
  • 1
Orkun
  • 6,998
  • 8
  • 56
  • 103
0

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.

Stefan
  • 4,645
  • 1
  • 19
  • 35