Spoiler: this post may contain something stupid due to being used to C and new to Java programming
There is an activity MainActivity and a public non-activity class containing a number of methods. I need to show toast alerts for some of them
Current attempts are something like this, which fails with "Non-static method can not be referenced from a static context" for getApplicationContext():
void errorWarn (String warning) {
Context context = android.content.ContextWrapper.getApplicationContext();
Toast.makeText(context, "Something's wrong in " + warning, Toast.LENGTH_SHORT).show();
}
So, how to call toasts from a non-activity class?
UPD: The errorWarn is to be called from the methods in the class. So, if an error in a method of the class occurs, there should be an alert
We are in the MainActivity having an editText field. The class should get and parse the string from it. If on some step processing fails, it shows a toast in the MainActivity
UPD2: The full structure.
MainActivity:
public class MainActivity extends ActionBarActivity {
<...>
public void ButtonClick (View view) {
Class.testfunc("");
}
}
Class:
public class Class {
void errorWarn (Context context, String warning) {
Toast.makeText(context, "Something must be wrong. " + warning, Toast.LENGTH_SHORT).show();
}
void testfunc (String string) {
errorWarn(string);
}
}
static void errorWarn (Context context, String warning) { ... }
as when you need to show the toast you always can have a proper context – Sibel