繁体   English   中英

JAVA中的全局变量替代方案

[英]global variables alternatives in JAVA

我还是Android应用程序开发的新手。

我在QSLite数据库中有一个表,它为我提供了关于每个用户的关键参数。 典型的表格如下图所示;

在此输入图像描述

当用户登录到应用程序时,我想设置一些我可以在整个应用程序中使用的常量。 例如,如果上表中UserID = 3的用户登录,我想获取此UserID(CurrentUserID)。 然后,我将使用该ID从应用程序活动中的任何位置检查他是来自位置2,还是来自哪个DataSourceID。 结果将确定我应该向用户显示/提供哪种类型的活动。

在Access中,我们使用了全局变量。 但是,根据我在java中读到的内容,不推荐使用公共静态变量(等效)。

您能否指出一些如何在Java中解决这样的挑战的例子?

创建单个对象并使用值填充它

http://en.wikipedia.org/wiki/Singleton_pattern

您只需要使用SharedPreferences: http//developer.android.com/guide/topics/data/data-storage.html#pref

您可以扩展Application类 - 它一个单例 - 并将变量保存为字段或属性

在你的清单中你定义了这样的类:

<application
    android:name="com.something.SingletonApplication"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

例如,您可以使用静态字段定义类来存储全局值

class Globals {
   public static int var1;
   public static String var2;

   //and so on
}

您可以通过这种方式访问​​此变量

Globals.var1 = 1;
Globals.var2 = 2;

如果您希望变量为常量,请将“final”添加到任何变量声明中

如果要确保在整个应用程序生命周期中可以使用您的变量,则可以扩展Application类

public class MyApplication extends Application
{

  private int userId;

  @Override
  public void onCreate()
  {
    super.onCreate();


  }
  public void setUserId(int id){
     this.userId = id;
  }
  public void getUserId(){
     return this.userId;
  }


  public void customAppMethod()
  {
    // Custom application method
  }

您还可以创建单例类并继续引用扩展应用程序类的类,但在大多数情况下这并不是必需的,因为单例对象将保留在内存中,直到应用程序收到内存警告。

不要忘记添加清单文件:

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

暂无
暂无

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

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