Reputation: 3383
With Firebase
database and user object, it's possible to load every information from the database whenever the user navigates through different activities but to save some time it seems more effective for the data to be loaded on the MainActivity
and put into one object (like user.setProfile
) and for that object to be accessed from every Activity
. Is this possible and how ? (a simple example would be very appreciated ).
Upvotes: 2
Views: 2444
Reputation: 1610
One possible solution will be to use your application class.
class FbprojectApplication extends Application{
static UserObject user;
public static void setUserObject(UserObject user){
this.user=user;
}
public static UserObject getUserObject(){
return user;
}
}
In android Application class has lifecycle throughout application, Hence can be called using activities whenever required.
Now from your activity,
public class MainActivity extends Activity{
//initialize userobject whenever you need to.
void initializeUser(UserObject user){
FbprojectApplication.setUserObject(user);
}
}
Similarly this variable will be available from any class.
public class OtherActivity extends Activity{
//get userobject whenever you need to.
FbprojectApplication.getUserObject();
}
As userobject is static in application class you can reinitialize it without worrying about inconsistency across different activities.
Upvotes: 1
Reputation: 24211
I would like to suggest having a static
object declared in the launching Activity
. Then you can get the values from all other Activity
once its populated with the values fetched from Firebase.
Upvotes: 0
Reputation: 2795
a good way to handle this sort of dependency through your app is to use a dependency injection framework, such as dagger http://square.github.io/dagger/
if you want to be lazy you can keep a object in your application class, this will then be available to any activity.
Upvotes: 0
Reputation: 45
You should have a try for the Singleton design pattern, and don't forget about the thread safe problem.
Reference: Singleton pattern
Upvotes: 1