Search code examples
androidandroid-context

Tried to access UI constants from a non-visual Context


I am running my image viewer app in StrictMode to try to catch up memory leaks. In the activity that shows many thumbnails I see an error several times (probably once for each thumbnail):

E/ViewConfiguration: Tried to access UI constants from a non-visual Context:android.app.Application@7f56ef7UI constants, such as display metrics or window metrics, must be accessed from Activity or other visual Context. Use an Activity or a Context created with Context#createWindowContext(int, Bundle), which are adjusted to the configuration and visual bounds of an area on screen
java.lang.IllegalArgumentException: Tried to access UI constants from a non-visual Context:android.app.Application@7f56ef7

This error is being triggered in the getView method of an ImageAdapter class extending BaseAdapter:

    ....
    public View getView(int pos, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.thumbitem, parent, false);
            ...

This line convertView = inflater.inflate... is the one that gives the error.

The class has the following method that also triggers a Tried to access visual service LayoutInflater from a non-visual Context error:

ImageAdapter() {
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
    }

So it seems my inflater has a wrong context? Which would be the correct one?


Solution

  • Which would be the correct one?

    Your Activity is the correct Context. Ideally, call getLayoutInflater() on your Activity and use it.