Apperside
Apperside

Reputation: 3602

Android context over the whole application

this question is intended to ask to the community if the approach i've taken for my app is correct or may have some side effect:

I've created: - an Activity, called MasterAcitity, extended from every activity in my app. The application tag in the manifest is declared as follow

<application
        android:name="my.package.name.MyApplication"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/ApplicationStyle" >

MasterActivity executes this code in OnResume and OnCreate methods

MyApplication.setContext(this);

Every activity of the app extends MasterActivity.

There is a class in the app, called DialogHelper which has a static method

public static void showDialog(String message)

which uses android.app.AlertDialog.Builder to create and show a dialog using as context MyApplication.getContext()

so from everywhere in my app i can use

DialogHelper.showDialog("my message");

Is this approach going to work? or i need to pay attention to something?

My doubt is on the static context...

Thanks

Upvotes: 1

Views: 403

Answers (2)

k3b
k3b

Reputation: 14755

You should also have a onDestroy handler that resets the context to null if the context belongs to the activity beeing destroyed.

Instead of a global static context i would prefer a api like this

 DialogHelper.showDialog(this.getContext(),"my message");

[Updated 5.5.2013]

Every Activity, Service , BroadcastReceiver is indirectly derived from Context via ContextWrapper and other classes like Views save and use Context. they normally expose it through a getContext() function. So the context should be available where neccessary.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006584

Is this approach going to work?

Using an Application for UI work has a history of causing problems. Either use an Activity, or a specialized Context for a given set of circumstances (e.g., getThemedContext() on ActionBar, getContext() on a Presentation).

Upvotes: 1

Related Questions