General Android Advice: Global Variables

醉酒当歌 提交于 2019-12-11 18:23:01

问题


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.

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?

Thanks for any help!


回答1:


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...

}

Then you just refer to it in your code as:

Global.getInstance().getUserList();

etc.



来源:https://stackoverflow.com/questions/15368815/general-android-advice-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!