Reputation: 5504
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.
Upvotes: 0
Views: 90
Reputation: 6556
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;
Upvotes: 0
Reputation: 1933
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
Upvotes: 1