Attempt to invoke virtual method in Resources res = getResources();

前端 未结 2 2041
生来不讨喜
生来不讨喜 2020-12-12 03:21

I am trying to change the background color of an activity using a handler, but I am getting an error \"Attempt to invoke virtual method\".

Here is my code

         


        
2条回答
  •  -上瘾入骨i
    2020-12-12 03:27

    You invoke the method getResources() as part of the class initialisation (outside of any method, so it will be executed as part of the constructor)

    At this point, the Activity instance does not yet exist so it may not call methods which require the existence of the instance.

    Statements which will cause an Exception because they take advantage of the fact that an Activity is a kind of Context:

    android.content.res.Resources res = getResources();
    int[] clrItems = res.getIntArray(R.array.color_background);

    The following statement on the other hand will not cause problems because it's just plain old Java:

    List arrayOfColor = new ArrayList();

    Simply paste the "problem statements" into a method, e.g. onCreate()

    // declare here
    android.content.res.Resources res;
    int[] clrItems; 
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // initialise here
        res = getResources();   
        clrItems = res.getIntArray(R.array.color_background);
    
        relativeLayoutMain = (RelativeLayout) findViewById(R.id.relativeLayoutMain);
    
        Button btnSignIn = (Button) findViewById(R.id.buttonSignIn);
        btnSignIn.setEnabled(false);
    
        ...
    }
    

提交回复
热议问题