user2312638
user2312638

Reputation: 443

In android how do I call StartActivity() from a global function?

So I'm trying to make a Logout function that all the logout butotns would call.

I found this page creating global functions in android

and I started coding a global function, and it refuses to recognize startActivity()

Here's my code

import android.content.Intent;

public class Utilities {


public static void Logout(){
    System.out.println("Logging Out");
    Intent i = new Intent(getBaseContext(), MainActivity.class);
    startActivity(i);
 }
}

getBaseContext() also gives me an error but I was able to find another fix for that (I think, haven't been able to test it).

Upvotes: 1

Views: 3239

Answers (3)

Raghunandan
Raghunandan

Reputation: 133560

You will need the activity context.

 public class Utilities {
 public static void Logout(Context context){
 Log.i("Utilities","Logging Out");
 Intent i = new Intent(context, MainActivity.class);
 context.startActivity(i);
 }
 }

startActivity is a method of your activity class. So you will need the activity context.

http://developer.android.com/reference/android/content/Context.html#startActivity(android.content.Intent)

Upvotes: 3

codeMagic
codeMagic

Reputation: 44571

You should try passing Context of the Activity to it.

public class Utilities {

    public static void Logout(Context c) {
        System.out.println("Logging Out");
        Intent i = new Intent(c, MainActivity.class);
        c.startActivity(i);
    }
}

So when you call it from an Activity

However, another way to do this is to create a BaseActivity which extends Activity and have the function in there. Then extend all of your Activities from BaseActivity and use an <include tag to include the Button in each layout file maybe as a header, footer, or whatever.

Utlities.Logout(this);

Upvotes: 0

petey
petey

Reputation: 17150

Add param of your current activity (from). Then call your static method with it.

public static void Logout(Activity from){
    System.out.println("Logging Out");
    Intent i = new Intent(from, MainActivity.class);
    from.startActivity(i);
 }
}

Upvotes: 0

Related Questions