Android - Spinner setting TextView visible/invisible - java

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

Related

Spinner wont show selected and wont respond to item selection

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)

Index out of bounds in a Spinner

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

Finding out the parent of clicked element in android ListView

I'm building my first app based on material from http://javatechig.com/video/json-feed-reader-in-android.
Everything goes ok so far, but I found one bug with ListView elements, which I can not manage to resolve by myself :(
I have extended list_row_layout.xml by 2 fields:
<Button
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="komcie"
android:textSize="11sp"
android:id="#+id/loadComments"
android:layout_gravity="center|bottom"
android:background="#bbb"
android:layout_marginLeft="5dp"
android:enabled="true"
android:clickable="true"
android:onClick="clickedLoadComments"
android:elegantTextHeight="true"
android:layout_toRightOf="#id/thumbImage"
android:layout_below="#+id/content"
android:padding="1px" />
<ListView
android:id="#+id/comment_list"
android:layout_toRightOf="#id/thumbImage"
android:layout_below="#+id/content"
android:paddingTop="5dp"
android:layout_marginTop="0dp"
android:paddingLeft="5dp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:cacheColorHint="#00000000"
android:dividerHeight="1dp"
android:focusable="false"
android:listSelector="#drawable/list_selector_flatcolor"
android:visibility="invisible" />
Button.android:onClick="clickedLoadComments" function load Json with elements into ListView/comment_list. It works quite fine. But if there are more elements than could be displayed on screen (~8 elements) there is a bug. Comments from clicked element are loaded into every 8th element in a ListView.
Some code:
public void clickedLoadComments(View v)
{
try {
View parent = (View)v.getParent();
ViewHolder t = (ViewHolder) parent.getTag();
if( parent != null ) {
this.loadCommentsForLeaf(parent);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected void loadCommentsForLeaf( View view )
{
String tmpUrl = "http://some.url.com/Ajax/LoadComments?lid=" + this.currentLeafInUse;
JSONObject commentsJson = this.getJSONFromUrl(tmpUrl);
this.parseJsonComments(commentsJson);
if( commentsJson != null )
this.updateCommentList(view);
}
public void updateCommentList( View view) {
commentListView = (ListView) view.findViewById(R.id.comment_list);
commentListView.setVisibility(View.VISIBLE);
CommentListAdapter cla = new CommentListAdapter(this, this.commentList.get(this.currentLeafInUse));
commentListView.setAdapter(cla);
// Set list height.
ViewGroup.LayoutParams params = commentListView.getLayoutParams();
params.height = setListViewHeightBasedOnItems(commentListView) + 20;
commentListView.setLayoutParams(params);
commentListView.requestLayout();
}
CustomListAdapter.java code is mostly the same as the one in tutorial.
I would really appreciate help as I have spent many hours figuring it out with not success :(
This is just a guess. You might post your Adapter code and your parseJsonComments also if this does not work.
The Cause:
The problem you are describing might be caused due to the recycling and the reusage of Views. Take a look at this image from http://android.amberfog.com
As you can see the 1. items is reused and becomes the 8. item after scrolling.
Let's assume that Item 1 has an OnClickListener which updates a Text of the item.
For example we set the text to "clicked" after the OnClickListener is triggered.
Because item 1 is reused to create item 8, item 8 will also display the text "clicked".
The Solution:
The usual way is to save all states/content in a List(or whatever) and update everything in the getView call. So if you want to update text:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
...
holder.textView.setText(jsonTexts[position]);
...
return convertView;
}
And if you want to update an item just update the List in your Adapter which holds the content/JsonObjects(etc.) and call notifyDataSetChanged.
public void updateCommentList(JSONObject commentsJson, int position) {
// does not exist you might create something
//like that in your Adapter class
commentListAdapter.updateItem(commentsJson,position);
commentListAdapter.notifyDataSetChanged();
}
After i populate the listview i call this method:
private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.lv);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
String xx = position+ ":" + id;
//then you can do what ever you want
}
});
}

android java set fix default value for spinner

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.

Custom Array Adapter Returning Blank Screen?

I'm still very new to application development, so this is probably a very stupid question but I can't seem to find the right answer (or at least one that I can understand with my very limited knowledge of java).
I'm using a custom ArrayAdapter called ListRow. It works fine with a regular Activity, but not with the ListActivity that I need it to be in for my app to work.
Below is a sample of the code that I'm using. Any help would be greatly appreciated and you'd be helping a ton!
ListView mListview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ListRow(this, THEME_NAMES, THEME_ICONS));
getListView().setTextFilterEnabled(true);
}
public class ListRow extends BaseAdapter {
private Context mContext;
private String[] mThemeNames = THEME_NAMES;
private int[] mThemeIcons = THEME_ICONS;
public ListRow(Context c, String[] t, int[] i) {
mContext = c;
mThemeNames = t;
mThemeIcons = i;
mListview=(ListView)findViewById(R.id.list);
}
#Override
public int getCount() {
return mThemeNames.length;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View converView, ViewGroup parent) {
View List;
if(converView==null){
List=new View(mContext);
LayoutInflater mLayoutinflater=getLayoutInflater();
List=mLayoutinflater.inflate(R.layout.list_view, parent, false);
} else {
List = (View)converView;
}
ImageView imageView = (ImageView)List.findViewById(R.id.image);
TextView textView = (TextView)List.findViewById(R.id.text);
imageView.setImageResource(mThemeIcons[position]);
textView.setText(mThemeNames[position]);
return List;
}
}
And here's the layout I've defined for each list item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="center"
android:id="#+id/image"
android:layout_alignParentLeft="true"
android:contentDescription="#string/preview" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/image" />
</RelativeLayout>
If you can, please use small words with me lol, java has turned out to be hard to understand for me, and also try to explain as much as you can. Thanks in advance!
FIGURED IT OUT!
So I just put you all through a bit of hell. The layout that contains my list items is called list_item, not list_view. However I have learned a lot here so THANK YOU ALL VERY MUCH! I wish there were a way I could help you guys out...
Moral of this question? CHECK YOUR LAYOUT NAMES!!
You need to set The Adapter in this way
setListAdapter(new ListRow(this, your_theme_names_array, your_theme_icon_array));
You dont need to use ArrayAdapter for this, that is just for Creating a Adapter for an array of String
EDITED
The Layout XML does not have the problem i think.
Check the List given below one by one
Check List
Check Whether R.layout.list_view point to the layout you given in the Question.
Try this for setting adapter setListAdapter(new ListRow(this, String[] { }, int[] { })); it will show you blank screen (If you get the Blank Screen that means either THEME_NAMES or THEME_ICONS is null or their values is null)
Remove the Line imageView.setImageResource(mThemeIcons[position]); and
textView.setText(mThemeNames[position]); this will also give u blank screen (If you get blank screen then R.layout.list_view does not contain R.id.image or R.id.text.
You have to add your mListView in your ArrayAdapter in setListAdapter.Only then the contents of your listview will be display in the pattern you have mentioned in customadapter. I cannot see where you have added elements in listview.

Categories

Resources