如何在Android中使用全局类变量 [英] How to use global class variables in android

查看:478
本文介绍了如何在Android中使用全局类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里做一个应用程序.我正在使用全局类变量.它运行良好,但是如果我使用更多的globalclass变量,则有时会出现内存异常.

Hi I am doing one app here. I'm using global class varibles. It's working well, but if I'm using more globalclass variables I'm getting memory exceptions some times.

我尝试过:

  public class SecondClass extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);



    TextView tv = (TextView)findViewById(R.id.tv);
    tv.setText("Global String : " + GlobalClass.myVal);
}
 }


  class GlobalClass extends Application {

   static String myVal;

  }

这是正确的吗?

推荐答案

首先,您不需要静态变量即可在应用程序类中声明全局变量,

First thing, you dont need Static Variable to declare global variable in Application Class,

因此将您的代码更改为:

so Change your code to:

class GlobalClass extends Application {

   public String myVal;

  }

然后,在需要访问此数据的任何地方,均可通过以下方式获取Application对象:

then whereever you need to access this data, get Application object by:

GlobalClass global=(GlobalClass)context.getApplication();
global.myVal="anything";

这篇关于如何在Android中使用全局类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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