2

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 ).

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You should have a try for the Singleton design pattern, and don't forget about the thread safe problem.

Reference: Singleton pattern

2 Comments

I know the singleton pattern works in Java it needs to create constructor but what about in activities ... ?? How you can make it work there ?
Create a singleton class and just use its instance in the Activity class. All you need to do is providing the interfaces needed. For example, private T userProfile, public T getUserProfile(), public void setUserProfile(T).
0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.