Alex Martian
Alex Martian

Reputation: 3812

android "cannot resolve method" error using application object

I have MainActitity where in onCreate:

BLEApplication mApp = (BLEApplication) BLEApplication.mAppContext();
        mApp.MainActivity = this;

Also in MainActitity

public void EnableDisableButtons(){
            findViewById(R.id.buttonNewGame).setEnabled(true);
    }

Class:

public class BLEApplication extends Application {
static Activity MainActivity;

... }

public class BLE {
...

BLEApplication mApp = (BLEApplication) BLEApplication.mAppContext();        
mApp.MainActivity.EnableDisableButtons();
        mApp.MainActivity.findViewById(R.id.buttonContinueGame).setEnabled(true);

I can use MainActivity.findViewById to enable activity buttons from class BLE but for EnableDisableButtons() Studio says "cannot resolve method". I can copy all code from EnableDisableButtons to BLE, but using method in MainActivity seams to me more elegant solution. Why it gives error?

Upvotes: 0

Views: 1494

Answers (1)

Damanpreet Singh
Damanpreet Singh

Reputation: 726

I Am not able to fully understand your code. But as per java concept you need to typecast Activity to your activity like this:

public class BLE {
...

BLEApplication mApp = (BLEApplication) BLEApplication.mAppContext();        
((MainActivity)(mApp.MainActivity)).EnableDisableButtons();
        mApp.MainActivity.findViewById(R.id.buttonContinueGame).setEnabled(true);

Since your mApp.MainActivity is object of Activity so you need to typecast it to tell which Activity it is , so that it can find the method that you have declared in your activity.

Also mApp.MainActivity gives you object of Activity class in which there is no EnableDisableButtons() method hence this error is there. Now if you typecast it to MainActivity it will find the method and this error will not come.

Upvotes: 1

Related Questions