Reputation: 43
I'm developing a simple app in which I want to maintain a session in all the activities until the user logs out. I am new to android so please give me good explanations or webside references or any other stuff for session maintaining.
Thank you.
Upvotes: 1
Views: 2076
Reputation: 1571
you can use the Application class in you activity. By extending the Application class you can maintain the state in android throughout the application. It means you can call those variables in the application in all the activity.
public class SampleApplication extends Application {
private static String username;
private static String password;
@Override
public void onCreate() {
super.onCreate();
username="";
password="";
}
public static String getUsername() {
return username;
}
public static void setUsername(String username) {
SampleApplication.username = username;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
SampleApplication.password = password;
}
}
by using this code you can set and get the username and password in any activity. And maintain the state of your username and password. Just you need to add the class name in the manifest.xml like this way.
<application
android:name=".SampleApplication"
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SampleApp"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You can access you application variables with static getters and setters from any activity or service. :
SampleApplication.setUsername("");
String currentUserName=SampleApplication.getUsername();
SampleApplication.setPassword("");
String currentPassword=SampleApplication.getPassword();
Hope you get your answer by this sample.
Upvotes: 1