0

In my android project I have some activity classes, and also simples java classes. There are some of them are independent of contextes and views totally, but in others duly I need it for to access a particular method of context.

I have read about it, and some people says they pass the context of some activity to every class that need its methods; others that pass a view and then get the context or that this classes have to extend of Activity... ¬¬

But for example, I have a class where it only calls once a method of context like:

getSharedPreferences(configNameFile, 0);
getString(R.string.text);
...

Therefore I would like to know what pattern do you use to do this always.

Fran b
  • 3,016
  • 6
  • 38
  • 65
  • I think Google provides a solution where we can obtain the global context of our app if we have a class extends to Application. So something this seems better: `public class App extends Application{ private static SakebuApp instance; public void onCreate() { super.onCreate(); instance = this; } public static Context getContext(){ return instance.getApplicationContext(); } }` – Fran b Aug 16 '12 at 16:48

2 Answers2

1

My personal favorite ways to do this is:

Dependency injection using RoboGuice

or

Make sure you don't need the context

If possible, try to avoid using the context in other files then your activity. If it is really needed, I write a wrapper most of the time. E.g. for Settings, I write a Settings interface that is able to do it with shared preferences. Whenever you want to change your settings implementation later, it is easily done by swapping the implementation of your interface. If you really need it, I'd prefer using a static Application context

Community
  • 1
  • 1
Jordi
  • 1,357
  • 12
  • 20
  • I like these options but I have a doubt. If we understand android's architecture like MVC pattern: `Java Class -> Model; Activity -> Controller; View -> View` Therefore all classes that won't be Models should be Activities and then always there is a context. But I am not sure it. – Fran b Aug 15 '12 at 18:58
  • I don't agree on your statement about `Java Class -> Model`. I'd say that an Android Service should be your model (because it is not tight to the lifecycle of your activity. In this service, you will always have a context. – Jordi Aug 16 '12 at 07:01
0

Also, you could make that method accept a Context paramerter, for example:

public void getPrefs(Context context){
   context.getSharedPreferences(configNameFile, 0);
   context.getString(R.string.text);
}

Then in your Activity pass the current context to it:

public void getPrefs(this);
Andy Res
  • 15,963
  • 5
  • 60
  • 96