简体   繁体   English

Android如何通过不同的Activity访问同一个对象

[英]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 .使用Firebase数据库和用户对象,可以在用户浏览不同活动时从数据库加载所有信息,但为了节省一些时间,将数据加载到MainActivity并放入一个对象(如user.setProfile ) 并从每个Activity访问该对象。 Is this possible and how ?这是可能的吗? (a simple example would be very appreciated ). (一个简单的例子将不胜感激)。

You should have a try for the Singleton design pattern, and don't forget about the thread safe problem.您应该尝试使用单例设计模式,不要忘记线程安全问题。

Reference: Singleton pattern参考:单例模式

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.在 android 应用程序类在整个应用程序中具有生命周期,因此可以在需要时使用活动调用。

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.由于 userobject 在应用程序类中是静态的,您可以重新初始化它,而不必担心不同活动之间的不一致。

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/通过您的应用程序处理此类依赖项的一个好方法是使用依赖项注入框架,例如 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.如果你想偷懒,你可以在你的应用程序类中保留一个对象,然后任何活动都可以使用它。

I would like to suggest having a static object declared in the launching Activity .我建议在启动Activity声明一个static对象。 Then you can get the values from all other Activity once its populated with the values fetched from Firebase.然后,一旦填充了从 Firebase 获取的值,您就可以从所有其他Activity获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM