Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

android - Calling context.getResources() returns null

So I am trying to get a string resource in my project but when I called context.getResources().getString(...), I get a NullPointerException. In debug mode, I found out that the context isn't null but looking at its members, I found out that mResources was null. Why are the resources not loaded for the activity context?

EDIT

Apparently, this is what triggered the Exception

public class MyActivity extends Activity {

    SomeClass someClass = new SomeClass(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}


public class SomeClass {

    private final Context mContext;

    public SomeClass(Context context) {
        mContext = context;
        mContext.getResources().getString(R.string.app_name);
    }
}

I had to move the initialization of someClass to after super.onCreate() as suggested by CommonsWare. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I had to guess, you are trying to call this in an initializer. Do not attempt to use getResources() before the super.onCreate() call in your activity returns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...