Home > Net >  is possible to keep an object across all the activities/fragment?
is possible to keep an object across all the activities/fragment?

Time:11-15

i would like to have a "global" object that persist in the application, even when you start other activity or fragment, its kind of annoying to use a bundle to pass the same elements in the app. Maybe with viewmodels? i dont know too much about that , so it would be handy if you give me an example or some guidance in this subject. Thank you in advance:)

CodePudding user response:

Basically it's pretty simple.

Step 1: Create a java class which extends the Application.

import android.app.Application;

public class MyApplication extends Application {

    public String yourObj;

    public String getYourObj() {
        return yourObj;
    }

    public void setYourObj(String yourObj) {
        this.yourObj = yourObj;
    }
}

Step 2: Define the Application name as your class.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.someProject">

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round">
        ...
    </application>

</manifest>

Here add android:name=".MyApplication" inside <application/> tag.

Step 3: Now use this where you want inside your application.

((MyApplication) getApplication()).setYourObj("...");
((MyApplication) getApplication()).getYourObj();

That's it :)

CodePudding user response:

I ended using something similar to an static var, but there is no static var in kotlin, so i used companion objects, it can store a variable perfectly :)

class ApplicationData {
   companion object {
      var string:String? =null
   }
 }

and its called from any activity or fragment as follows: ApplicationData.string = "Hi, im a string"

CodePudding user response:

Create a static object in a seperate file that you can reference in your project, so you can get and set it's data.

object MyStaticClass{
    static var myStaticVar : String = "Hello world"
}

Reference it in your files by doing:

MyStaticClass.myStaticVar = "A different message"

I have had to do this in the past where I had to save a user's login data to use through the app to change account data. This is so miuch easier than having to pass the data between views CONSTANTLY :)

  • Related