1

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?

bruno
  • 2,213
  • 1
  • 19
  • 31
Narek
  • 38,779
  • 79
  • 233
  • 389

5 Answers5

4

Trying making that argument final:

public void FbShare(final JSONObject parameters) {
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • `final` in java is the same as `const` in C++? Does it mean that I cannot change the values of `parameters` argument? – Narek Oct 15 '14 at 14:13
  • No, not the same. final says the reference won't change. Java is pass by value, and for objects the value is a reference type. You can't change the reference, but you can change the mutable state of the object the reference points to if it allows you to. const in C++ is a much wider ranging keyword. – duffymo Oct 15 '14 at 14:16
  • You mean the reference cannot point to other object, or the object it is pointing will not be changes inside the function. – Narek Oct 15 '14 at 14:18
  • I think I was clear: the reference itself cannot change. – duffymo Oct 15 '14 at 14:19
4

Set the parameters parameter as final:

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

For an overview of what's happening, see:

bruno
  • 2,213
  • 1
  • 19
  • 31
2

Change the first line to

public void FbShare(final JSONObject parameters) {
Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
1

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); 
           }
      };
slim
  • 40,215
  • 13
  • 94
  • 127
0

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

SMA
  • 36,381
  • 8
  • 49
  • 73