skip to Main Content

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:)

2

Answers


  1. Chosen as BEST ANSWER

    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"


  2. 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 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search