Application Context einmal definieren

  • Antworten:5
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

30.03.2013, 23:31:00 via Website

Hallo,
ich möchte meinen Context des ganzen Projektes (nehme an der ist überall gleich)
in einer Funktion Festlegen und dann diese von überall aus allen andern Klassen aufrufen.
Geht das?
Ich hätte das so gedacht:
1public class MyActivity extends Activity
2{
3public void onCreate(..)
4{
5...//Was da halt so rein kommt
6...
7}
8
9
10public static Context getContext()
11{
12MyActivity ma = new MyActivity();
13Context c = ma.getApplicationContext();
14return c;
15}

Und aus einer andern Klasse dann abrufen:
1MyActivity.getContext();
So etwas wäre schön, denn dann müsste ich den Application Context nicht mher Kreuz und quer übergeben.

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Steffen S.
  • Forum-Beiträge: 63

31.03.2013, 07:57:54 via App

So hatte ich es in einer App von mir mal gelöst:
1public class MainActivity extends Activity
2{
3 public static Context globalAppContext = null;
4
5 @Override
6 public void onCreate(Bundle savedInstanceState)
7 {
8 super.onCreate(savedInstanceState);
9
10 globalAppContext = getApplicationContext();
11
12 setContentView(R.layout.main);
13 ...
14 }
15}
damit konnte ich aus jeder Klasse dann mit:
1MainActivity.globalAppContext
auf den Context zugreifen.

hoffe das hilft dir weiter

PS.:
jede Activity hat soweit ich noch weiß einen eigenen Context.
Und dann gibt es noch den ApplicationContext, der unterscheidet sich aber etwas vom anderen Context.

— geändert am 31.03.2013, 08:40:46

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

31.03.2013, 10:09:32 via App

Danke ich werde es so versuchen.

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
TheEvilOne
  • Forum-Beiträge: 311

31.03.2013, 10:33:26 via App

Du kannst auch einfach ne Klasse machen mit ner statischen Activity- oder Context-Variable und diese beim Appstart zuweisen.

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

31.03.2013, 10:42:29 via Website

Du meinst, dass ich eine Klasse machen soll, deren statische Variable in der ersten Activity setze?
Das kann ich natürlich auch machen.

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Steffen S.
  • Forum-Beiträge: 63

31.03.2013, 10:43:34 via App

ja, das geht natürlich auch.

Antworten