Narek
Narek

Reputation: 39881

Pass function argument to callback function in Java

I have this code:

public void FbShare(JSONObject parameters) {

    if (Session.getActiveSession() == null || !Session.getActiveSession().isOpened()) {

        Session.StatusCallback callback = new Session.StatusCallback() {

            @Override
            public void call(Session session, SessionState state, Exception exception) {

                if (state.isOpened()) {
                    publishFeedDialog(parameters);  // <--- HERE
                }
            }
        };

        Session.openActiveSession(this, true, callback);
    } else {
        publishFeedDialog(parameters);
    }
}

Why is parameters not accessible in the publishFeedDialog(parameters)call?

Upvotes: 1

Views: 3705

Answers (5)

bruno
bruno

Reputation: 2273

Set the parameters parameter as final:

public void FbShare(final JSONObject parameters) {
 //...    
}

For an overview of what's happening, see:

Upvotes: 4

slim
slim

Reputation: 41223

The compiler error message tells you everything you need to know, if you can decipher it:

 Cannot refer to the non-final local variable parameters in an enclosing scope

That is, the variable parameters in the enclosing scope is not final, so it can't be referred to.

To fix that, make it final:

 public void FbShare(final JSONObject parameters) {

Java isn't clever enough to keep track of what parameters refers to, unless you use final to guarantee that it's always going to point at the same object.

This would equally apply if you were referring to a local variable that wasn't a method parameter:

 public void foo() {
      final String bar = ...;
      Callback callback = new Callback() {
           void invoke() { 
               something(bar); 
           }
      };

Upvotes: 1

SMA
SMA

Reputation: 37023

Make your parameters as final so it can be used within your anonymous class.

Upvotes: 0

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Change the first line to

public void FbShare(final JSONObject parameters) {

Upvotes: 2

duffymo
duffymo

Reputation: 308753

Trying making that argument final:

public void FbShare(final JSONObject parameters) {

Upvotes: 4

Related Questions