There are 4 Spinnners:
resiko,untung1,untung2,untung3
The user picks resiko first to proceed and the app will show which Spinner will be visible (untung1/untung2/untung3)
Trying to make dynamic data Spinner, when you click an item inside the first Spinner, the others will be gone, and the desired one will be visible, working so far.
The problem is is when i pick "tinggi" from the Spinner resiko, it get an error: java.lang.IndexOutOfBoundsException
I also tried reading other posts, but still not sure what should I do.
I tried using getSelectedItem() before, but when I want to take the desired data from the visible Spinner, which is selected by the user, the app didn't pick the selected item itself, instead it picked the first data in the visible Spinner.
(let's say there's 2 value in the Spinner, A and B; the user pick B, but the program picks A)
in example:
the user picks "rendah" in the "resiko" Spinner, and then the next visible Spinner is untung2, then the user picks "sedang" in that Spinner,
but the program picks "--pilih--" instead of "sedang"
That's why I switched to getItemAtPosition(position).toString();
strings.xml
<string-array name="spinner_resiko_string">
<item>--Pilih--</item>
<item>Sangat Rendah</item>
<item>Rendah</item>
<item>Sedang</item>
<item>Tinggi</item>
</string-array>
<string-array name="spinner_return_string">
<item>--Pilih--</item>
<item>Rendah</item>
</string-array>
<string-array name="spinner_return_string2">
<item>--Pilih--</item>
<item>Rendah</item>
<item>Sedang</item>
</string-array>
<string-array name="spinner_return_string3">
<item>--Pilih--</item>
<item>Rendah</item>
<item>Sedang</item>
<item>Tinggi</item>
</string-array>
spinner declaration :
final Spinner resiko = (Spinner) mScrollView.findViewById(R.id.spinner_resiko);
final Spinner untung1 = (Spinner) mScrollView.findViewById(R.id.spinner_return1);
final Spinner untung2 = (Spinner) mScrollView.findViewById(R.id.spinner_return2);
final Spinner untung3 = (Spinner) mScrollView.findViewById(R.id.spinner_return3);
spinner in xml :
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_return1"
android:entries="#array/spinner_return_string"
android:layout_marginLeft="10dp"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_return2"
android:entries="#array/spinner_return_string2"
android:layout_marginLeft="10dp"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_return3"
android:entries="#array/spinner_return_string3"
android:layout_marginLeft="10dp"/>
code version 1 (error index out bound when i pick "tinggi" in resiko spinner ) [ using getItematPosition ] :
resiko.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> mRelative, View selectedItemView, int position, long id) {
String resikox = mRelative.getItemAtPosition(position).toString();
if (resikox.equals("Sangat Rendah")) {
untung1.setVisibility(View.VISIBLE);
untung2.setVisibility(View.GONE);
untung3.setVisibility(View.GONE);
untungx = untung1.getItemAtPosition(position).toString();
}
else if (resikox.equals("Rendah")){
untung1.setVisibility(View.GONE);
untung2.setVisibility(View.VISIBLE);
untung3.setVisibility(View.GONE);
untungx = untung2.getItemAtPosition(position).toString();
}
else if (resikox.equals("Sedang") || (resikox.equals("Tinggi"))) {
untung1.setVisibility(View.GONE);
untung2.setVisibility(View.GONE);
untung3.setVisibility(View.VISIBLE);
untungx = untung3.getItemAtPosition(position).toString();
} else {
untung1.setVisibility(View.GONE);
untung2.setVisibility(View.GONE);
untung3.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
version 2 ( using getItemSelected )
//set spinner
resiko.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> mRelative, View selectedItemView, int position, long id) {
String resikox = mRelative.getItemAtPosition(position).toString();
if (resikox.equals("Sangat Rendah")) {
untung1.setVisibility(View.VISIBLE);
untung2.setVisibility(View.GONE);
untung3.setVisibility(View.GONE);
untungx = untung1.getSelectedItem().toString();
}
else if (resikox.equals("Rendah")){
untung1.setVisibility(View.GONE);
untung2.setVisibility(View.VISIBLE);
untung3.setVisibility(View.GONE);
untungx = untung2.getSelectedItem().toString();
}
else if (resikox.equals("Sedang") || (resikox.equals("Tinggi"))) {
untung1.setVisibility(View.GONE);
untung2.setVisibility(View.GONE);
untung3.setVisibility(View.VISIBLE);
untungx = untung3.getSelectedItem().toString();
} else {
untung1.setVisibility(View.GONE);
untung2.setVisibility(View.GONE);
untung3.setVisibility(View.GONE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
logcat :
12-23 19:37:23.221 30433-30433/com.example.fabio.tabdrawer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.fabio.tabdrawer, PID: 30433
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.Arrays$ArrayList.get(Arrays.java:66)
at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:337)
at android.widget.AdapterView.getItemAtPosition(AdapterView.java:831)
at com.example.fabio.tabdrawer.Menu_PIAF$1.onItemSelected(Menu_PIAF.java:183)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:964)
at android.widget.AdapterView.access$200(AdapterView.java:49)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:928)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Your <item>--Pilih--</item> is causing a problem, as it is taking up the position of the first item of your spinner. So by the time you select the last item, Tinggi it throws an index out of bounds error.
This will give you advice on how to create a non-selectable item at the top of your spinner: How to make an Android Spinner with initial text "Select One"
You can change the visibility to gone, that is a good idea, however you need to implement separate onItemSelectedListeners for each spinner.
resiko,untung1,untung2,untung3 as they are separate elements and have varying sized arrays.
Although it seems like more work, it's important to keep UI elements interactions separate.
Now if there is a method that is common to a user selection, this can be modularised.
Example:
So if several different item selections cause the background color to turn yellow in a method called:
turnBackgroundYellow()
then this method can be placed in as many on item selected events as you please.
However the reverse does not work.
Each unique spinner needs to have it's listeners attached to it specifically for that spinner.
Make these class variables, so you can pass them as parameters into a class method.
String resikox_;
String untung1_; // and the others
// Create an ArrayAdapter using the string array and a default spinner layout
// Create a separate one for each spinner resiko,untung1,untung2,untung3
ArrayAdapter<CharSequence> adapter = ArrayAdapter
.createFromResource(getActivity(), R.array.dataobjects_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
resiko.setAdapter(adapter);
// Create a separate one for each spinner resiko,untung1,untung2,untung3
resiko.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
resikox_ = parent.getItemAtPosition(position).toString();
SelectedItemMethod(resikox_)
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//DO WHATEVER OR NOTHING
}
});
// Class method to do your item selection stuff.
public void SelectedItemMethod(String item){
if (item.equals("Sangat Rendah")) {
untung1.setVisibility(View.VISIBLE);
untung2.setVisibility(View.GONE);
untung3.setVisibility(View.GONE);
}
//etc, etc for all your spinners or break it up, as you please
Add separate setOnItemSelectedListener() for each spinner
Related
I'm trying to make a very very simple spinner at least, as follows:
XML:
<Spinner
android:id="#+id/spinner_categories"
android:layout_width="0sp"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:layout_weight="1"
android:textColor="#000000"
android:spinnerMode="dropdown"/>
JAVA:
spinnerCategories = findViewById(R.id.spinner_categories);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_spinner_item,
categories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategories.setAdapter(adapter);
Log.d(Utilities.LOG_FLAG, "SPINNER: " + spinnerCategories.toString());
spinnerCategories.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(context, categories.get(position).toString(), Toast.LENGTH_SHORT).show();
Log.d(Utilities.LOG_FLAG, "SELECTED");
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
Log.d(Utilities.LOG_FLAG, " NOT SELECTED");
}
});
I can see the entire list, but once I click on an item, nothing happans, and it wont show the selection at all, even if I use setSelection(), and if I try to do spinnerCategories.getSelectedItem().toString() I get a NullPointerException.
I tried searching the web a lot, but none solution seems to help me...
Edit
For some reason when I load the page and then I go out of the page and reenter it, only then it will show the selected items of the spinner
On the first load it shows for a very brief second and then it's gone until the page is reentered the second time
The setOnItemSelectedListener gets triggered when you click on an element from the drop down menu .. to fetch the selected item you need to use .getSelectedItemPosition() something like
categoriesList.get(spinner.getSelectedItemPosition)
What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.
UPDATE:
I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.
So this is my code for 1st activity, I will just put only one first :
btnAsia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("continent", "asia");
startActivity(intent);
}
});
This is the string array in strings.xml:
<string-array name="asia">
<item>Japan</item>
<item>Thailand</item>
<item>Vietnam</item>
<item>South Korea</item>
</string-array>
and this is the code in 2nd activity:
private void DestinationSpinner()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String continent = bundle.getString("continent");
switch (continent) {
case "asia":
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
break; }
and lastly this is the code for retrieve selected item from spinner:
public void AvailableAirlines()
{
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected=spinnerDestination.getItemAtPosition(position).toString();
if (continent.equals("asia") && selected.equals("Japan"))
{
availableAirlines.setText("Available airports");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.
I think the issue is this line if(selected=="Japan")
In Java you will need to use equals instead of the == operator.
The == checks if the two pointers are pointing to the same memory location.
Equals will compare their content.
I'm trying to do my first Spinner, and I have encountered some difficulties, such as that I don't know if I can get an option by spinner.getSelectItem == "some string".
Take a look at my code so far
Populating the spinner:
public void addItemsOnSpinner() {
Spinner buttonSpinner = (Spinner) findViewById(R.id.buttonSpinner);
List<String> list = new ArrayList<String>();
list.add("Ultimos 5 lancamentos");
list.add("Ultimos 7 lancamentos");
list.add("Ultimos 10 lancamentos");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
buttonSpinner.setAdapter(dataAdapter);
}
Trying to make an if statement:
if(buttonSpinner.getSelectedItem().toString() == "Ultimos 10 lancamentos"){
textView.setVisibility(View.VISIBLE);
}
TextView code as requested:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Deposito"
android:visibility="invisible"
android:id="#+id/textView"
android:layout_row="2"
android:layout_column="0"
android:layout_gravity="center|left" />
And its code on the class:
TextView textView = (TextView)findViewById(R.id.textView);
Yes you can do it and it will work fine, but please use
buttonSpinner.getSelectedItem().toString().equals("Ultimos 10 lancamentos");
As Stefano has pointed out, your comparison should be using equals (which compares the String contents, vs == which compares the object references).
Otherwise your if statement should work, however its not clear where you are calling it from (and that might be the cause of the problem). If you want to make the comparison immediately after a spinner item is selected then you need to set an OnItemSelectedListener and make the comparison there.
Here is an example of how you might declare this listener inline:
buttonSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getSelectedItem().toString();
if (selectedItem.equals("Ultimos 10 lancamentos"))
{
textView.setVisibility(View.VISIBLE);
}
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
I would like to have a fix value that is always displayed in the Spinner and when clicking on the Spinner this value should not be listed in the drop down selection.
Until now I have the following
Definition XML:
<Spinner
android:layout_width="76dp"
android:layout_height="40dp"
android:id="#+id/right_shift"
android:layout_row="0"
android:layout_column="0"/>
Java:
final Spinner right = (Spinner) findViewById(R.id.right_shift)
ArrayList<String> rightShift = new ArrayList<String>();
rightShift.add(" >>"); //THIS SHOULD BE THE VALUE THAT IS ALWAYS DISPLAYED
for (int i=0; i<5; i++)
...//add other values to arraylist
...//set values of arraylist to spinner
right.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
right.setSelection(0);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
But when clicking on the Spinner the preselected Item will again be shown in the drop down and the right.setselection(0) is not executed fast enough so I still see the selected Item for about 0.5sec... Is there an other/easier way to perform this?
you can add
android:prompt=" >>"
in xml and in java set default position in spinner to be -1.
I followed steps in how to change value of textview according to selected item and here is a piece of the code
public void onCreate(Bundle savedInstanceState){.......
final TextView privacyTextView = (TextView) findViewById(R.id.eventPrivacy);
privacySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id3) {
final String selectedItem = parent.getItemAtPosition(position).toString();
privacyTextView.setText(selectedItem);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
list is :
<string-array name="privacy_levels">
<item>Everyone</item>
<item>Friends of Friends</item>
<item>Friends Only</item>
<item>Customize</item>
</string-array>
I have text view with value : privacy when running app it's automatically changed to Everyone -frist one on the list- so what is going wrong ?!!!
Add android:prompt in Spinner xml and set a name like
android:prompt="Privacy";
So first time it will show privacy then user can select from the drop down list.
Try this...!
final String selectedItem = parent.getSelectedItem().toString().trim();
privacyTextView.setText(selectedItem);
If you want to get first item as privacy then you need to add another item in your array as Privacy.
There is a attribute called android:spinnerMode this is used to get the spinner in two modes as dialog or dropdown.
where as the attribute android:prompt is to get the spinner Title or Heading after opening it(in Dialog mode).
Just try to this so you will get selected string:
String name = spinner.getSelectedItem().toString();