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

Issue

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.

Solution

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);

Answered By – Pouria Rezaie

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published