一般的Andr​​oid忠告:全局变量 [英] General Android Advice: Global Variables

查看:98
本文介绍了一般的Andr​​oid忠告:全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是来处理Android应用程序的全局变量的最佳途径。例如,我只是想创建一个基本的登录/注册系统。我创建了一个用户类(即具有各种属性像用户名,密码等),这样,当我们去登记活动中,用户类的构造函数被调用来创建一个唯一的用户对象,一旦所有的领域都充满出。当时我想的是只要有User类型的全球ArrayList的,这样我可以通过刚上的所有登录尝试的用户环路。

I was wondering what is the best way to handle global variables for android apps. For example, I'm just trying to create a basic login/register system. I've created a user class (that has various attributes like username, password, etc..), so that when we go to the register activity, the User class constructor is called to create a unique user object once all the fields are filled out. I was then thinking of simply having a global arrayList of type User so that I could just loop through all the users on a login attempt.

到目前为止,(由于组合缺乏java的经验,是非常新的这个机器人的东西),我一直没能成功地实现这一点。我有一个类,我称之为globalStuff,它有一堆公共静态变量(即用户列表和当前用户),我认为可以从用户导航到任何活动进行访问的。

So far (due to a combined lack of experience in java, and being very new to this android stuff), I haven't been able to implement this successfully. I have a class which I call "globalStuff" which has a bunch of public static variables (i.e. the list of users and current user), which I thought could be accessed from any activity the user navigates to.

必须有一个更好的方式去这件事。我一直在读通过一些教程和这里几个帖子,但没有解决这个很基本的想法。所以,这将是接近这样的事情的最好方法?

There must be a better way to go about this. I've been reading through a few tutorials and a few posts on here, but none address this very basic idea. So what would be the best way to approach something like this?

感谢您的帮助!

推荐答案

这就是所谓的静态单,它看起来是这样的:

It's called a static singleton and it looks like this:

public class Global {

    private static Global instance = null;

    public static Global getInstance() {
        if( instance == null )
            instance = new Global();
        return instance;
    }

    // additional methods, members, etc...

}

然后你只需指它在你的code为:

Then you just refer to it in your code as:

Global.getInstance().getUserList();

等。

这篇关于一般的Andr​​oid忠告:全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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