Android Context变为null

Seb*_*Seb 5 java android

在我的申请中

类中心实例化如下:

central.java:

mContext = getApplicationContext();
mMyStuff = new MyStuff(mContext);
Run Code Online (Sandbox Code Playgroud)

MyStuff类需要从某些资源获取mContext.

MyStuff.java:

public class MyStuff {

    private Context  mContext;

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

    ....    
    private ActionCustom MyAction = new ActionCustom(mContext);
Run Code Online (Sandbox Code Playgroud)

问题是mContext始终为null,即使c不为null.我在做新的MyStuff(mContext)时期待

ρяσ*_*я K 6

问题是mContext始终为null,即使c不为null

因为目前:

private ActionCustom MyAction = new ActionCustom(mContext);
Run Code Online (Sandbox Code Playgroud)

在调用MyStuff类构造函数之前执行的行,其中mContext对象的初始化完成.

这样做:

private ActionCustom MyAction;
public MyStuff(Context c) {
    mContext = c;
    MyAction = new ActionCustom(mContext);
}
Run Code Online (Sandbox Code Playgroud)


小智 -1

代替

public MyStuff(Context c) {
    mContext = c;
}
Run Code Online (Sandbox Code Playgroud)

尝试

public MyStuff(Context c) {
    this.mContext = c;
}
Run Code Online (Sandbox Code Playgroud)