2015-07-03 10 views
5

In meiner AnwendungAndroid Kontext ist null geworden

die Klasse zentrale wird instanziiert als wie unten:

central.java:

mContext = getApplicationContext(); 
mMyStuff = new MyStuff(mContext); 

MyStuff Klasse müssen die mContext bekommen von einigen zugreifen Ressourcen.

MyStuff.java:

public class MyStuff { 

    private Context mContext; 

    public MyStuff(Context c) { 
     mContext = c; 
    } 

    ....  
    private ActionCustom MyAction = new ActionCustom(mContext); 

Problem ist, dass mContext auch in c immer null ist, ist nicht null. Ich hatte erwartet, dass, wenn die neue MyStuff tun (mContext)

Antwort

-1

Statt

public MyStuff(Context c) { 
    mContext = c; 
} 

versuchen

public MyStuff(Context c) { 
    this.mContext = c; 
} 
+0

Sorry, aber es funktioniert nicht. Ich habe einen Haltepunkt auf diesem gesetzt.mContext = c aber es hört nie auf – Seb

+3

siehe ρяσѕρєя K's Antwort. Er ist wahrscheinlich richtig. – Laurens

+0

Was ist der Unterschied zwischen "mContext = c" und "this.mContext = c" in diesem Fall? –

6

Problem ist, dass mContext auch in c immer null ist, ist nicht null

Weil derzeit:

private ActionCustom MyAction = new ActionCustom(mContext); 

Zeile ausgeführt vor dem Aufruf MyStuff Klassenkonstruktor, wo die Initialisierung von mContext Objekt erfolgt ist.

Machen Sie es so:

private ActionCustom MyAction; 
public MyStuff(Context c) { 
    mContext = c; 
    MyAction = new ActionCustom(mContext); 
}