Home > Mobile >  How can I pass activities to a function in another class?
How can I pass activities to a function in another class?

Time:11-05

I am building a shop project for school, and as I decided that instead copying and pasting a function which toasts that there's no internet connection in each activity, I should instead add it to my project manager class, which is not an activity, ShopManager. The problem is, in order to toast, one of the parameters is the activity in which the toast should occur and I have not found a way to do it. I decided for now I should just try to toast before adding any internet checking, and this is what I created thus far:

This is in my Home Page activity:

public class Home extends AppCompatActivity implements View.OnClickListener {

    ShopManager shopMng;
...
...
...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        shopMng = new ShopManager();

        shopMng.toast(Home.this);
   }
}

In my ShopManager class:

public class ShopManager {

    public void toast(Class cls) {
        Toast.makeText(cls.this, "Test", Toast.LENGTH_SHORT).show();
    }

}

The error message I am getting is " 'toast(java.lang.Class)' in 'com.example.birthdayshop.ShopManager' cannot be applied to '(com.example.birthdayshop.Shop)' ", which I deducted basically means that the type of the cls parameter is not correct. What type of variable should it be in order to work in ALL activities? Thank you so much in advance.

CodePudding user response:

To answer the titled question, I think you'd have to pass an Intent to the method, which in your case doesn't make a whole lot of sense, e.g.,

Intent intent = new Intent(getApplicationContext(), Home.class);
shopMng.someMethod(intent);

To start the activity, you still need some context, so this should be disregarded as the solution, but could answer the titled question for others.

The standard way is to pass context or the activity itself, so to get your program working correctly, try this instead:

public class ShopManager {

    public void toast(Context context) {
        Toast.makeText(context, "Test", Toast.LENGTH_SHORT).show();
    }

}

or respectively:

public class ShopManager {

    public void toast(Home home) {
        Toast.makeText(home, "Test", Toast.LENGTH_SHORT).show();
    }

}

That's it! Your Home activity is already calling your toast method in your ShopManager class correctly. Good luck!

CodePudding user response:

make a static method in your ShopManager class that get context and shows toast like this:

public class ShopManager {
    static void toastMessage(Context context){
        Toast.makeText(context, "Test", Toast.LENGTH_SHORT).show();
    }
}

for calling it from your activity do this:

ShopManager.toastMessage(YourActivity.this);

  • Related