user6456773 user6456773 - 1 month ago 20
Android Question

How to get the prompt of a spinner via method?

I want to validate an EditText field in my android app. The field is spinner. The prompt is defined in the .xml. If I output it in the console, it appears correctly. However, when part of a Toast's structure, within a method, the address of the spinner is printed rather than the prompt:
Spinner validation in a validating class:

public static boolean spinnerValidated(Spinner spinner) {
return spinner.getSelectedItemPosition()==(0);

}


It's invocation in the main class:

private void validateSpinner(Spinner spinner) {
if (Utility.spinnerValidated(spinner)) {
Toast.makeText(getApplicationContext(),
"Invalid data for field " + spinner.getPrompt().toString(),
Toast.LENGTH_LONG).show();
}
}


Call of the method:

validateSpinner(spinner);


Spinner xml:

<Spinner
android:id="@+id/spinner"
style="@style/spinner"
android:background="@drawable/edit_text_rectangle"
android:spinnerMode="dialog"
android:prompt="@string/subcategory"/>


And the Style:

<style name="spinner">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">12dp</item>
<item name="android:layout_marginRight">12dp</item>
<item name="android:layout_marginBottom">5dp</item>
<item name="android:layout_marginTop">5dp</item>
<item name="android:paddingTop">8dp</item>
<item name="android:paddingBottom">8dp</item>
</style>

Answer

Toast doesn't need the global application context. The scope of this Toast is only for the Activity.

Change your context from getApplicationContext() to YourActivty.this.