创建对象通过在Android中中的所有活动访问 [英] Creating an Object accessible by all Activites in Android

查看:95
本文介绍了创建对象通过在Android中中的所有活动访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建数据的包含对象(如地址和属性(pretty复杂)的列表)一个ArrayList,我想知道:怎样才能让一个对象可访问(和编辑)所有活动和不只是一个它被实例化?

基本上这个:


  1. 在活动1创建阵列

  2. 在活动2和3访问同一个磁盘阵列

  3. ???

  4. 利润。


解决方案

要做到这一点,最简单的方法就是创建一个单例。这是一种只可一次创建的对象,如果您尝试访问再次将返回对象的现有实例。
这里面你可以拿着你的数组。

 公共类辛格尔顿{
    私有静态最终Singleton实例=新辛格尔顿();    //私有构造prevents从其他类实例
    私人辛格尔顿(){
    }    公共静态辛格尔顿的getInstance(){
        返回实例;
    }}

了解更多关于单:
<一href=\"http://en.wikipedia.org/wiki/Singleton_pattern\">http://en.wikipedia.org/wiki/Singleton_pattern

I'm trying to create an ArrayList of Data containing Objects (Like a list of Addresses and properties (pretty complex)) and am wondering: How can I make an Object accessible (and editable) by all Activities and not just the one it was instanciated in?

Basically this:

  1. Create Array in Activity 1
  2. Access same Array in Activity 2 and 3
  3. ???
  4. Profit.

解决方案

The easiest way to do this is by creating an Singleton. It's a kind of object that only can be created once, and if you try to access it again it will return the existing instance of the object. Inside this you can hold your array.

public class Singleton  {
    private static final Singleton instance = new Singleton();

    // Private constructor prevents instantiation from other classes
    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }

}

Read more about singleton: http://en.wikipedia.org/wiki/Singleton_pattern

这篇关于创建对象通过在Android中中的所有活动访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆