Henok
Henok

Reputation: 3383

Android how to access the same object through different activities

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

Answers (4)

farhan patel
farhan patel

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

Reaz Murshed
Reaz Murshed

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

Matthew Shearer
Matthew Shearer

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

jules3c
jules3c

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

Related Questions