0

I'm trying to implement a basic login in my app. What I want to do is set a "Global" variable as true / false if user is logged in.

I've followed this tutorial. So this is my code now:

import android.app.Application;

public class GlobalParameters extends Application{
    private boolean loggedIn;

    public boolean isLoggedIn() {
    return loggedIn;
    }

    public void setLoggedIn(boolean loggedIn) {
    this.loggedIn = loggedIn;
    }
}

And this is on my onCreate:

GlobalParameters gp = ((GlobalParameters)getApplicationContext());
gp.setLoggedIn(false);

But GlobalParameters gp = ... throws this exception:

ClassCastException

I've added this too in my manifest:

<application android:name=".GlobalParameters" 
   android:icon="@drawable/ic_launcher" 
   android:label="@string/app_name">
</application>

Any idea?

Thanks.

Community
  • 1
  • 1
Reinherd
  • 5,476
  • 7
  • 51
  • 88

2 Answers2

1

Use this.getApplication() to get the Application associated with your Activity. But I think in your case, going to the Application is a bit overkill. You could just use a static field in a class.

However, if you want the state to be retained when your Activity is discarded then you can use SharedPreferences, a good guide to get started with those is here https://developer.android.com/guide/topics/data/data-storage.html#pref

chopchop
  • 1,905
  • 2
  • 22
  • 37
0

If your variable is just to login and logout, is better you use a static variable and set it true on login and set it false on logout.

public static boolean loggedIn;

and use it as below:

myApplication.loggedIn = true;

myApplication.loggedIn = false;
Victor Laerte
  • 6,446
  • 13
  • 53
  • 102