问题
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.
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.
回答1:
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
}
Now in your Activity:
//after setContentView
TestApplication testAppObj = (TestApplication) getApplication();
testAppObj.setSomeObj(myObj);
//retrieve as:
someObj = testAppObj.getterMethodOfObj();
You must register your Application class in your manifest file just like you register your activities:
<application
android:name="com.pkg.test.TestApplication " />
Hope this helps.
回答2:
You can create your custom Application (like others said) and then you will have a global access to this information but I think this is not a good design because your activities will be tied to this Application implementation (you will not be able to use this activities in a different App).
I suggest you to implement a Service and use this Service in all the activities.
Check the next article to create a background service which will be active for all the activities: https://developer.android.com/training/run-background-service/create-service.html
回答3:
Best way to implement this is to save data in Prefrences and retrieve whenever required. To simplify this you can directly store an Object in prefrences and get that object whenever required.
To save object you will require GSON library to be added in your libs folder and the you can conver any object to string and store anywhere you want like this.
Object-->>String >>> Gson gson = new Gson(); String json =gson.toJson(Object);
Getting object back
String -->> Object >>> Gson gson = new Gson(); Object obj =gson.fromJson(json string);
The above method will return in a persistent storage and you won't keep memory occupied all the time. Static variables can be freed by system on memory requirement, hence not recommended.
回答4:
The Application
way is the best, but if you want to check here is the official list of common ways to do that.
来源:https://stackoverflow.com/questions/26503124/create-a-common-object-for-whole-application