14

I am using the Facebook Android SDK and want to close my Activity after a user logs in and gets the user object. In practice I am storing parts of it but I want to close the activity regardless.

      // make request to the /me API
      Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

        // callback after Graph API response with user object
        @Override
        public void onCompleted(GraphUser user, Response response) {
          if (user != null) {
           finish(); // causes errors
          }
        }
      });

The IDE error message on finish() is: "Cannot make a static reference to the non-static method finish() from the type Activity"

how to proceed?

CQM
  • 42,592
  • 75
  • 224
  • 366

2 Answers2

31

Create a reference to your activity in onCreate with

//onCreate
final Activity activity = this;

Then you can use that in your onCompleted callback

activity.finish();

You might have to make Activity activity global.

EDIT 2/26/2014:

Note that calling finish() from a static method is probably bad practice. You are telling a specific instance of an Activity with it's own lifecycle that it should shut itself down from a static method, something without any lifecycle or state. Ideally you'd call finish() from something with a binding to the Activity.

bclymer
  • 6,679
  • 2
  • 27
  • 36
  • something like this worked! `static Activity activity;` no more errors, we will see what happens I compile :) – CQM May 06 '13 at 16:29
  • I'm glad, if it works please mark the question as correct so that this no longer remains as "unanswered". – bclymer May 06 '13 at 16:31
  • yes, it worked as intended, I finally compiled it, thank you! – CQM May 06 '13 at 16:55
6

For some, bclymer's method may not work. It didn't on mine, using the latest beta version Android Studio... Try this...

public class myActivity extends Activity {

    public static Activity activity = null;
    ...
    ...

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myActivity_layout);

        activity = this;
        ....
        ....
    }
}

from your other activity within the same package, simply ....

    // use try catch to avoid errors/warning that may affect the 
    // next method execution
    try {
         myActivity.activity.finish();
    } catch (Exception ignored) {}
sam byte
  • 697
  • 9
  • 11