Creating a common object for the entire application

I created one activity that creates a user profile and stores their information like name, id, profile, etc.

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

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

I have read about bundle and JSON but cannot figure out how to use it.

Please help me which option to choose. I've read a lot, but I'm not sure. Please help me what to do and what will be better.

+3


source to share


4 answers


You can use a class Application

to access the same object in many actions.

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 the manifest file exactly the same way you register your actions:

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

      

Hope it helps.

+4


source


You can create your own application (like others said) and then you have global access to this information, but I think this is not a very good design because your actions will be tied to this implementation of the application (you won't be able to use this activity in another app).

I suggest that you implement the Service and use this service in all your activities.



Check out the following article to create a background service that will be active for all activities: https://developer.android.com/training/run-background-service/create-service.html

+1


source


The best way to do this is to store the data in Prefrences and retrieve it when needed. To simplify this, you can directly store the object in prefrences and retrieve it as needed.

To store an object, you need to add the GSON library to the libs folder, and you can convert any object to a string and store it anywhere you want.

Object ->> String ->> Gson gson = new Gson (); String json = Gson.toJson (object);

Getting the object back

String →> Object →> Gson gson = new Gson (); Obj object = gson.fromJson (json string);

The above method will return to persistent storage and you won't be consuming memory all the time. Static variables can be deallocated by the system on demand, so not recommended.

0


source


The best way Application

, but if you want to check here , this is the official list of common ways to do it.

-1


source







All Articles