java静态存储,使用类存储在Java中的静态数据?

Is it a bad idea creating a separate class and use it as a storage which consists only of static data variables?

I am currently developing an app for android, but the question is general for Java.

In case of android, I am moving across activities and I would like to store some global/static flags/varibles in that separate class and being able to access them from any activity I want.

PS. The data is required only for the session time.

解决方案

Well, that's not a bad idea. You can use such type of a class in Android. But a small correction here. Instead of maintaining a class that holds static Data, you can make that class to extend Application class and use it store the data.

Here is a example,

public class HelloApplication extends Application {

private int globalVariable=1;

public int getGlobalVariable() {

return globalVariable;

}

public void setGlobalVariable(int globalVariable) {

this.globalVariable = globalVariable;

}

@Override

public void onCreate() {

//reinitialize variable

}

}

And in your Activity, do this,

(HelloApplication)getApplication()).setGlobalVariable(10);

int valiable=((HelloApplication)getApplication()).getGlobalVariable();

And speak about SharedPreference, you should consider using them only when the value has to be stored for a long time. if not, you should make use of the Application class and use setters and getters which is the legitimate way to do this.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值