跨类访问数组值 [英] accessing array values across classes

查看:105
本文介绍了跨类访问数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,其中包括的声明

I have an activity which includes a declaration of

public String progressArray[][] = new String[3][3]

在另一个文件(服务)我想访问该数组的值。 I code:

In another file (a service) I want to access the values of this array. I code:

ListViewLoader lvl = new ListViewLoader

现在我发现, lvl.progressArray [0] [0] 虽然我知道数据已经摆在它自己的类返回null。这是因为一个新的实例犯规包含原始值,如果是这样我怎么能访问在原有的价值观?

Now I find that lvl.progressArray[0][0] returns null although I know that data has been put in it in its own class. Is this because a new instance doesnt contain the values of the original, if so how can I access the values in the original?

推荐答案

您的解决方案是行不通的,因为progressArray是一个实例变量,同时呼吁

Your solution is not working, because progressArray is an instance variable and while calling

ListViewLoader lvl = new ListViewLoader

其中(在这种情况下,空)创建新实例progressArray设置为默认值。制作progressArray静态可以是一个快速的解决方案,但要注意,你将高度依赖于顺序活动和服务将访问阵列,它可能是当你的活动是由系统破坏复位。我强烈建议这样做,你劝阻。相反,请考虑延长应用类并实施名单初始化/访问那里,这样的:

which creates new instance with progressArray set to default value (null in that case). Making progressArray static can be a fast solution, but be aware you will highly depend on order in which activity and service will access that array and it may be reset when your activity is destroyed by system. I'm strongly discouraging you from doing that. Instead, please consider extending Application class and implement list initialisation / access there, like:

public class MyApplication extends Application {
    public String progressArray[][] = new String[3][3];
}

然后声明它AndroidManifest这样的:

Then declare it in AndroidManifest like:

<application
            android:name=".MyApplication"
            android:label="@string/app_name"
            android:icon="@drawable/icon">

那么这两个,从你的活动和服务,您可以通过调用

Then both, from your activities and services you can get that by calling

((MyApplication) getApplication()).progressArray

这是跨一个应用程序共享活动和服务之间的状态的唯一方法我所知道的,既不涉及发送消息来回,以保持状态保持一致(可以是平凡的任务),也没有使用单因素(的这是反模式,你可能知道)。

This is the only way to share state between activities and services across one application I'm aware of, neither involving sending messages back and forth to keep state consistent (which can be nontrivial task) nor using singletons (which is anti-pattern as you probably know).

但请记住,这需要以这种方式共享的可变数据可能是一种提示,您的设计需要改进。

But please keep in mind, that need of sharing mutable data in that manner may be a hint, that your design needs an improvement.

这篇关于跨类访问数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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