为整个应用程序创建一个公共对象

问题描述:

我创建了一个活动,该活动创建用户个人资料并存储其信息,例如名称,id,个人资料图片等.

I have created one activity that creates user profile and stores its information like name,id, profile pic etc.

此信息是唯一的,应在应用程序的所有活动中使用.

This information is unique and should be use in all activities in application.

我想知道哪种方法是创建存储所有信息并在所有活动中使用它的公共对象的最佳方法.

I want to know which is best way to create a common object that stores all information and use it in all activities.

我已经阅读了bundle和JSON,但不了解如何使用它.

I have read about bundle and JSON but can't understand it how to use it.

请帮助我选择什么选项.我已经读了很多书,但到目前为止还不确定.请帮助我做什么标准的事情,什么会更好.

Please help me as to what option should I choose. I have done a lot of reading but not sure as of now. Please help me with whats the standard thing to do and what would be better.

您可以使用Application类在许多活动中访问同一对象.

You can use Application class for accessing same object across many activities.

public class TestApplication extends Application {

    //Object declaration

    public TestApplication () {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate() { 
        // TODO Auto-generated method stub
        super.onCreate();
    }

    //setter getter for object
}

现在在您的活动中:

//after setContentView
TestApplication testAppObj = (TestApplication) getApplication();
testAppObj.setSomeObj(myObj);

//retrieve as:
someObj = testAppObj.getterMethodOfObj();

您必须在清单文件中注册Application类,就像注册活动一样:

You must register your Application class in your manifest file just like you register your activities:

<application
        android:name="com.pkg.test.TestApplication " />

希望这会有所帮助.