Spinner Listener not executed in Android - android

As a continuation of the question here, I found that the listener of the spinner is never executed (or) triggered and I am not able to solve the issue.
Here is the part of the code with the spinner and the listener:
Spinner priority = (Spinner)findViewById(R.id.priority);
priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("listener","it works");
Log.d("value",""+parent.getSelectedItem().toString().equalsIgnoreCase("Low"));
/*if(parent.getSelectedItem().toString().equalsIgnoreCase("Low"))
imageId = R.drawable.blue;
else if(parent.getSelectedItem().toString().equalsIgnoreCase("Medium"))
imageId = R.drawable.green;
else
imageId = R.drawable.red;*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
In the log, the values of listener and value are not printed at all.

Modified code.
Spinner priority = (Spinner)findViewById(R.id.priority);
priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("listener","it works");
//Instead of doing parent.getSelectedItem(), get the adapter from parent and from that adapter get item at position as below.
Log.d("value",""+parent.getAdapter().getItem(position).toString().equalsIgnoreCase("Low"));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If your data is string then it will work else you are passing any custom object then you need to cast result from this parent.getAdapter().getItem(position) to that custom object class.

Finally found the solution :
String priortyStr = priority.getSelectedItem().toString();
int imageId = 0;
if(priortyStr.equals("Low"))
imageId = R.drawable.blue;
else if(priortyStr.equals("Medium"))
imageId = R.drawable.green;
else
imageId = R.drawable.red;

Related

How to read what is actually inside a ListView and not the position it is in on android app?

I have an ListView which I have populate with a dynamic ArrayList and I used an OnItemClickListener to make it does something when i click on them (Code bellow).
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,txtOnlyList);
returnSaveNotesList.setAdapter(arrayAdapter);
AdapterView.OnItemClickListener noteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
if(position == 0 ) {
Intent intent = new Intent(ReadFromFile1.this, SaveAndRstoreNote.class);
intent.putExtra("firstNote","1 .txt");
startActivity(intent);
}
}
};
returnSaveNotesList.setOnItemClickListener(noteClickListener);
Now comes the tricky part, I want, somehow to be able to read what is actually written lets say on the position [0], the actual String. Is there any way to achieve that?
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
if (position == 0) {
String yourString = txtOnlyList.get(position);// use this
Intent intent = new Intent(ReadFromFile1.this, SaveAndRstoreNote.class);
intent.putExtra("firstNote", "1 .txt");
startActivity(intent);
}
}
Your ArrayAdapter<String> has a getItem() method that returns the String for a given position.
I have used the getItemAtPosition(position).
Here is the entire code:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,txtOnlyList);
returnSaveNotesList.setAdapter(arrayAdapter);
AdapterView.OnItemClickListener noteClickListener = new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
if(position == 0 ){
Intent intent = new Intent(ReadFromFile1.this, SaveAndRstoreNote.class);
String stringFromArray=txtOnlyList.getItemAtPosition(position).toString(); // I added this
intent.putExtra("firstNote","1 .txt");
startActivity(intent);
}
}
};
returnSaveNotesList.setOnItemClickListener(noteClickListener);
The View type parameter being passed in your OnItemClick function is the list item's view at that position.
AdapterView.OnItemClickListener noteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> txtOnlyList, View view, int position, long id) {
TextView tv = (TextView) view.findViewById(R.id.tv);
String text = tv.getText().toString(); //The required text is available in this variable
}
}

Issue with Spinner in the Listview

I have a button and Spinner in ListView item. I've put the below code inside setOnItemSelectedListener of Spinner.
String val = viewHolderItem.spinnerSize.getSelectedItem().toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
But it doesn't change inside the setOnItemSelectedListener. But when I put the same code inside setOnClickListener of the Button then it wroks and changed the value of the object. What is the reason for this?
GetView method :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderItem viewHolderItem;
final Shoe shoe = shoeList.get(position);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.component_order_shoe_row,null);
viewHolderItem = new ViewHolderItem();
viewHolderItem.tvName = (TextView)convertView.findViewById(R.id.tv_component_order_shoe_name);
viewHolderItem.tvPrice = (TextView)convertView.findViewById(R.id.tv_component_order_shoe_price);
viewHolderItem.tvDesc = (TextView)convertView.findViewById(R.id.tv_component_order_shoe_description);
viewHolderItem.ivPic = (ImageView)convertView.findViewById(R.id.iv_component_order_shoe_pic);
viewHolderItem.ivTick = (ImageView)convertView.findViewById(R.id.iv_component_order_shoe_tick);
viewHolderItem.spinnerSize = (Spinner)convertView.findViewById(R.id.spinner_component_order_shoe_size);
viewHolderItem.etQty = (EditText)convertView.findViewById(R.id.et_component_order_shoe_qty);
viewHolderItem.btnOrder = (Button)convertView.findViewById(R.id.btn_component_order_shoe_order);
viewHolderItem.btnOrder.setTag(viewHolderItem);
convertView.setTag(viewHolderItem);
}else{
viewHolderItem = (ViewHolderItem)convertView.getTag();
}
viewHolderItem.tvName.setText(shoe.getShoeName());
String text = String.valueOf(shoe.getPrice());
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;
if(decimalPlaces==1){
viewHolderItem.tvPrice.setText("Rs."+ text + "0");
}else{
viewHolderItem.tvPrice.setText("Rs."+ text);
}
if(shoe.isSelected()){
viewHolderItem.ivTick.setImageDrawable(mContext.getResources().getDrawable(R.drawable.tick));
viewHolderItem.btnOrder.setText(mContext.getResources().getString(R.string.btn_remove_shoe_item));
}else{
viewHolderItem.ivTick.setImageDrawable(null);
viewHolderItem.btnOrder.setText(mContext.getResources().getString(R.string.btn_order_shoes));
}
viewHolderItem.tvDesc.setText(shoe.getDesc());
Bitmap bmp = AppControl.convertStringToBitmap(shoe.getImg());
viewHolderItem.ivPic.setImageBitmap(bmp);
int smallest = shoe.getSmallestSize();
int largest = shoe.getLargestSize();
Integer[] arr = getSizeArray(smallest,largest);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(mContext, android.R.layout.simple_spinner_dropdown_item,arr);
viewHolderItem.spinnerSize.setAdapter(adapter);
viewHolderItem.btnOrder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewHolderItem viewHolder = ((ViewHolderItem) v.getTag());
boolean isSelected = shoe.isSelected();
if(isSelected){
((Button)v).setText(mContext.getResources().getString(R.string.btn_order_shoes));
viewHolder.ivTick.setImageDrawable(null);
viewHolder.etQty.setEnabled(true);
isSelected = false;
}else{
((Button)v).setText(mContext.getResources().getString(R.string.btn_remove_shoe_item));
viewHolder.ivTick.setImageDrawable(mContext.getResources().getDrawable(R.drawable.tick));
viewHolder.etQty.setEnabled(false);
isSelected = true;
}
shoeList.get(position).setSelected(isSelected);
String input = viewHolderItem.etQty.getText().toString();
if(isEnteredValueNumeric(input)){
shoeList.get(position).setQty(Integer.parseInt(input));
}else{
shoeList.get(position).setQty(1);
AppControl.showToastMessage(mContext,Constant.MSG_NOT_A_NUMBER);
viewHolderItem.etQty.setText(String.valueOf(1));
}
String val = viewHolderItem.spinnerSize.getSelectedItem().toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
}
});
viewHolderItem.spinnerSize.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String val = parent.getItemAtPosition(position).toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});
return convertView;
}
You made a mistake here:
String val = parent.getItemAtPosition(position).toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
The position value for shoeList is not the same as the position value for the shoeSize Spinner item. Try changing the onItemSelected method position name parameter to something like pos. So let your getView keep using final int position but in onItemSelected for shoeSize use:
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String val = parent.getItemAtPosition(pos)
.toString();
shoeList.get(position).setSelectedSize(
Integer.parseInt(val));
}
Inside your onClickListener's their is not any parameter for position as integer in onClickMethod:
#Override
public void onClick(View v) {
/* so this position in shoeList.get(position) returns the position of the
* list view item i.e you array list exact position*/
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
}
but in you onItemSelected their is a position value already exists so you may need to change it's parameter name like:
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// just like #electrocrat insist
String val = parent.getItemAtPosition(pos)
.toString();
shoeList.get(position).setSelectedSize(
Integer.parseInt(val));
}
you may also can do this via setting tag to viewHolderItem.spinnerSize as
viewHolderItem.spinnerSize.setTag(position) and inside the onItemSelected you can get the position via (Integer)parent.getTag(), like:
shoeList.get((Integer)parent.getTag()).setSelectedSize(
Integer.parseInt(val));

Spinner onitemclicklistener not working

I got a Spinner in my app and it does not work when an item is clicked. I get the values but the if condition is not getting worked.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
String Text = effecttwo.getSelectedItem().toString();
System.out.println("spinner is -"+item+"-");
// I get the correct values in System.out.println
if(Text=="Hue"){
// not entering into this condition or any other condition
}else if(Text=="Saturation"){
}else if(Text=="Brightness"){
}else{
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Please suggest me what I am doing wrong.
I get the values but the if condition is not getting worked.
if(Text=="Hue"){
Wrong
use .equals or .equalsIgnoreCase to compare strings
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)
if(Text.equals("Hue"))
{
}
What is the difference between == vs equals() in Java?
You dont compare string with ==. Use this:
if(text.equals("Hue"))
{
}
So your code goes this way:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
String Text = effecttwo.getSelectedItem().toString();
System.out.println("spinner is -"+item+"-");
// I get the correct values in System.out.println
if(text.equals("Hue")){
// not entering into this condition or any other condition
}else if(text.equals("Saturation")){
}else if(text.equals("Brightness")){
}else{
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Don't do the listener inside anonymous class.
Do it withspinner.setOnItemSelectedListener(this) and put implement AdapterView.OnItemSelectedListener after your fragment or activity.

Odd Android Spinner behavior

This is the code to populate my spinner.
The code:
String[] rcs = new String[review_cycles.length];
for (int i = 0; i < review_cycles.length; i++)
rcs[i] = review_cycles[i].ReviewCycleName;
ArrayAdapter<String> rc_spinnerAdapter = new ArrayAdapter<String>(
ActivityManagementReview.this,
R.layout.simple_spinner_item,
rcs);
sp_review_cycle.setAdapter(rc_spinnerAdapter);
sp_review_cycle.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
DtoMrReviewCycleVersion selected_review_cycle_version = review_cycles[position];
if (selected_review_cycle_version != latest_review_cycle_version) {
latest_review_cycle_version = selected_review_cycle_version;
int mr_version_id = latest_review_cycle_version.MrdVersionId;
_URL_version = _url_base + "MrVersion/" + Integer.toString(mr_version_id);
new GetMrVersionInfoAsyncTask().execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
return;
}
});
When I select a value from the spinner, the code is executed twice. Once with the selection I made and then right afterward, the first item in the list is executed again bringing me back to where I started.
How can I prevent this from happening?
Thanks.
When I select a value from the spinner, the code is executed twice.
As I reminded you in the comments, Spinners call onItemSelected() when they load the default value. This feature is useful when you know about it, but since it is not what the average developer expects it is problematic as well.
The Spinner will also call onItemSelected() when the user re-selects the current value... When I want to avoid both of these false alarms I use something like this:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
int previous = -1;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(previous != position && previous < -1) {
Log.v("Example", "Selected: " + position);
// Do something
}
previous = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});

How to refer to the original position of a list item when text filter is enabled?

When I use edit text to filter the items, the list positions get all messed up and the items no longer call the proper intent. Any help is appreciated
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String mName = filteredValues.get(position).getName().toString();
String mWeb = filteredValues.get(position).getWebsite().toString();
Intent openDetails = new Intent(Test.this, ResourceDetails.class);
Bundle b = new Bundle();
b.putString("name", mName);
b.putString("web", mWeb);
openDetails.putExtras(b);
startActivity(openDetails);
}
});
private TextWatcher filterTextWatcher = new TextWatcher(){
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
public void afterTextChanged(Editable s) {
}
};
flashsearchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Integer temp=flashSearchNameMap.get(adapter.getItem(position));
navigateSearch(temp);
}
});
(adapter.getItem(position) will return you the exact list name and in flashSearchNameMap i have stored names and position at beginning from oncreate before applying filtering.So you can get exact position by this
if you use ViewHolder in Adapter just define a realPosition variable in holder class and set it in YourAdapter.getView
and in listClick Listener
ContactAdapter.ViewHolder holder = (YourAdapter.ViewHolder) view.getTag();
holder.realPosition
The item position is not reliable when using lists. I recommend you to use view.setTag(Object) to assign an identifier to each item when attaching the content. This could be a number, string or anything. Then you can just access it with view.getTag() inside the click listener.
Assuming you are using a custom bean object to store your name & website values and an ArrayAdapter to show them in your ListView, like so
public class NamedLink {
final String mName;
final String mWebsite;
public NamedLink(String name, String website) {
mName = name;
mWebsite = website;
}
#Override
public String toString() {
return mName;
}
}
With an adapter, defined something like this:
mAdapter = new ArrayAdapter<NamedLink>(this, android.R.layout.simple_list_item_2, mLinks) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(WhateverYourActivityIsNamed.this).inflate(android.R.layout.simple_list_item_2, null);
}
NamedLink link = getItem(position);
// This probably deserves a ViewHolder
((TextView) convertView.findViewById(android.R.id.text1)).setText(link.getName());
((TextView) convertView.findViewById(android.R.id.text2)).setText(link.getWebsite());
return convertView;
}
};
When you filter the array adapter it will match against the beans #toString(), which in this case returns the name. When filtered, the array adapter maintains a properly indexed copy of your list of beans internally - i.e. you can use the position you get in the click listener like this:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getItemAtPosition() will return a NamedLink from the filtered
// list maintained inside the ArrayAdapter
NamedLink link = (NamedLink) parent.getItemAtPosition(position);
Intent openDetails = new Intent(Test.this, ResourceDetails.class);
Bundle b = new Bundle();
b.putString("name", link.getName());
b.putString("web", link.getWebsite());
openDetails.putExtras(b);
startActivity(openDetails);
}
});

Categories

Resources