首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在所有活动中传递参数?

问如何在所有活动中传递参数?
EN

Stack Overflow用户
提问于 2012-08-26 18:57:45
回答 3查看 217关注 0票数 0

我正在开发一个移动应用程序,其中我需要用户对象在所有活动中都可用,并且我不想使用每个活动的意图将其发送到另一个活动。

有谁能帮帮我吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-08-27 22:37:21

只需将对象设置为'public static‘即可。然后在其他活动中访问它,如:

代码语言:javascript
复制
PreviousActivity.userobj
票数 1
EN

Stack Overflow用户

发布于 2012-08-26 19:10:11

如果您可以将其存储在:

我认为SharedPreferences的实现会简单得多。这里有一个例子,你如何创建一个静态函数,你可以从你的所有活动中访问:

代码语言:javascript
复制
public class UserCreator
{
    public static User getUser(Context context)
    {
        SharedPreferences prefs = context.getSharedPreferences("Name", Context.MODE_PRIVATE);

        //Check if the user is already stored, if is, then simply get the data from
        //your SharedPreference object.

        boolean isValid = prefs.getBoolean("valid", false);

        if(isValid)
        {
            String userName = prefs.getString("username", "");
            String passWord = prefs.getString("password", "");
            ...
            return new User(userName, passWord,...); 
        }
        //If not, then store data
        else
        {
            //for example show a dialog here, where the user can log in.
            //when you have the data, then:

            if(...login successful...)
            {
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("username", "someusername");
                editor.putString("password", "somepassword");
                editor.putBoolean("valid", true);
                ...
                editor.commit();
            }
            // Now, if the login was successful, then you can recall this function,
            // and it will return a valid user object.
            // if it was not, then it will show the login-dialog again.
            return getUser(context);
        }
    }
}

然后从你所有的活动中:

代码语言:javascript
复制
User user = UserCreator.getUser(this);
票数 3
EN

Stack Overflow用户

发布于 2012-08-26 19:02:16

编写一个扩展Application类的类。并将全局参数放在那里。这些参数将在应用程序上下文中有效。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12129522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档