I've created a simple class for my Android application called coreTuts. I'm done with tying it in to my MainActivity.java, activity_main.xml, and so on, like this:
MainActivity.java
coreTuts tuts = new coreTuts();
public void displayToast(View view)
{
tuts.sampleToast();
}
coreTuts.java looks like:
coreTuts.java
public class coreTuts{
//Do a toast notification
public void sampleToast()
{
Toast toast = Toast.makeText(getActivity().getApplicationContext(),
"This is a message displayed in a Toast",
Toast.LENGTH_SHORT);
toast.show();
}
}
I couldn't decide whether I should usegetActivity().getApplicationContext()or just getApplicationContext() on my Toast because either code doesn't work.
In fact, these are my questions:
- I understand contexts in Android are kinda like habitats to animals. Am I right if I look at
getActivity()andgetApplicationContext()that way? - How do I make
getApplicationContext()work in another class so that I can run mytoast, or is that even allowed?
Thank you!
your coreTuts should be like below
and you can invoke it like below,
Note: view cannot be null