0

我正在开发一个移动应用程序,我需要在所有活动中都可以使用用户对象,并且我不想使用 Intent 从每个活动发送它到另一个活动。

谁能帮帮我?

4

3 回答 3

3

如果您可以将其存储在:

我认为 SharedPreferences 实现起来会简单得多。这是一个示例,您可以如何创建一个静态函数,您可以从所有活动中访问它:

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);
        }
    }
}

然后从您的所有活动中:

User user = UserCreator.getUser(this);
于 2012-08-26T11:10:11.123 回答
1

只需将该对象设为“公共静态”即可。然后在其他活动中访问它,例如:

PreviousActivity.userobj
于 2012-08-27T14:37:20.517 回答
1

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

于 2012-08-26T11:02:15.777 回答