Search code examples
androidextend

Android extends Application and make an instance of it


I'm tried following code:-

public class LocationApplication extends Application {

public LocationInfo locationInfo;
public int myInt;
@Override
public void onCreate() {
    super.onCreate();
   }
}

public int getInt(){  
    someMethod(context);
    return myInt;
   }
}

Later in some other activity I have to get myInt that is in LocationApplication class. Note that I cannot make myInt static. So somehow I have to have an instance of LocationApplication class. So how do I make an instance of LocationApplication that is initialized by framework call chain earlier (means that onCreate() was called by framework).

Any other suggestion to achieve this goal?


Solution

  • In Android, when subclassing the Application class, you'll have to tell the framework that you'd like to use you that. The framework will keep only 1 instance of your Application subclass You do that by adding the following attribute to the application tag in your AndroidManifest.xml:

    android:name="com.example.android.LocationApplication"
    

    Replace the com.example.android with your own packageId.

    Your manifest could look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.android" >
    
        <application
            android:name="com.example.android.LocationApplication"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
    
            <!-- Omitted the rest of the XML -->
    
        </application>
    
    </manifest>
    

    Next, in your Activity (or anything that extends from Context), you call getApplication(). Cast that to LocationApplication and you have access to your Application object.

    That might look like this in your case:

    // In your Activity (or anything that extends Context)
    LocationApplication application = (LocationApplication) getApplication();
    int value = application.getInt()