Reputation: 4208
I have been searching on the Internet about how to create a Session in an Android application. I found this and it certainly helped me in a part of my project.
At present, I have a similar situation where in I have a Login application that asks the user to enter the username and password. On click of the submit button I create and initialize my Session object.
The problem I am facing now is the fact that I want to know whether I can use this object in various activities apart from my Login application activity. I also want to know that if the Session object contain user credentials , can it be send via a web service and stored in a remote database?
Upvotes: 0
Views: 3190
Reputation: 310
Sorry, i maybe very late here but i like to introduce two points :
1 - There are various ways of storing objects to be available everywhere in the app. You can use static objects, Singleton design pattern, Serialization...etc. Every choice has its conditions (mostly related to object size)
2 - The accepted answer above introduced by @Gabriel Negut is not recommended due to the manner that Android manages its applications lifecycles. A NullPointerException can be thrown when the application is restored with a new Application object. Philippe Breault has a nice article about that.
Upvotes: 0
Reputation: 13960
Create a class that extends Application
(don't forget to update your manifest file) and add to it the required fields (username, password and so on). This class will be available to all your activities. You can find a detailed explanation here.
Later edit:
Let's say you have a Session
class with username
as a field.
class Session {
public String username = "";
}
Next, extend the Application
:
class App extends Application {
Session session = new Session();
public String getUsername() {
return session.username;
}
public void setUsername(String username) {
session.username = username;
}
}
Now, when you want to access the username, you can do it from any activity:
App app = (App) getApplication();
String username = app.getUsername();
if (username.equals("")) {
// the user is not logged in, do something
}
Upvotes: 1
Reputation: 1584
Or else try using sharedpreference if requirements are basic. http://developer.android.com/guide/topics/data/data-storage.html voteup and accept answer if you find it useful
Upvotes: 1