NullPointerException at android.content.ContextWrapper

前端 未结 2 1239
失恋的感觉
失恋的感觉 2021-01-19 03:29

When I try to get a color via getResources().getColor(R.color.yellow) in a normal Activity I get this exception:

07-12 11:58:38.019: E/AndroidRu         


        
相关标签:
2条回答
  • 2021-01-19 04:02
    int backgroundColor = Color.YELLOW;
    

    instead of

    int backgroundColor = getResources().getColor(R.color.yellow);
    
    0 讨论(0)
  • 2021-01-19 04:12

    Your mDragListener is a member variable. At the point of initializing the Activity object/instance might not be ready. So calling getResource() of the Activity will fail.

    // inner class or normal class ... change scope if needed
    private class DragListener {
        int color = 0;
        public DragListener(Context context) {
            color = context.getResource().getColor(R.color.yellow);
        }
    }
    
    // activity
    private DragListener mDragListener;
    public void onCreate(...) {
        mDragListener = new DragListener(this);
        // more code
    }
    
    0 讨论(0)
提交回复
热议问题