Call finish () from static method

I am using the Android Android SDK and want to close my activity after a user logs in and receives a user object. In practice, I keep parts of it, but I want to close the action independently.

// 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 } } }); 

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

how to act?

+8
android android-activity static facebook-android-sdk
source share
2 answers

Link to your activity in onCreate with

 //onCreate final Activity activity = this; 

Then you can use this in your onCompleted callback

 activity.finish(); 

You may need to make Activity activity global.

EDIT 2/26/2014:

Note that calling finish() from a static method is probably bad practice. You specify a specific instance of an Activity with its own life cycle, which should shut itself off from the static method, something without any life cycle or state. Ideally, you would call finish() from something linked to an Activity .

+24
source share

For some, the bclymer method may not work. It's not my way using the latest beta version of 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 action in the same package, just ....

  // use try catch to avoid errors/warning that may affect the // next method execution try { myActivity.activity.finish(); } catch (Exception ignored) {} 
+3
source share

All Articles