Android: how get ID of an item selected in a spinner? - android

I have this private method to render a spinner in a fragment:
private void renderSpinner() {
List<String> spinnerArray = new ArrayList<String>();
for (int i = 0; i<mPromotionList.size(); i++) {
ModelPromotion modelPromotion = (ModelPromotion) mPromotionList.get(i);
String name_promotion = modelPromotion.getName();
int id_promotion = modelPromotion.getIdPromotion();
spinnerArray.add(name_promotion);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mBaseApp, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerPromotion.setAdapter(adapter);
mSpinnerPromotion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String name_promotion_selected = parent.getItemAtPosition(pos).toString();
//TODO REMOVE
Log.d(LOGTAG, "Il nome della promo selezionata è " + name_promotion_selected);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
As you can see, I have "ready" the id_promotion (It's the real value that I need)... And I know that I'm not adding (for now) at the List.
How I can get it, inside the onItemSelected?
Thank you very much

You can use the position of the selected item and use that to get the ID from the original list.
((ModelPromotion) mPromotionList.get(pos)).getIdPromotion()
Another option is to create a custom ArrayAdapter subclass that will accept ModelPromotion instead of String and override getItemId to return the idPromotion
An example about custom ArrayAdapter on Github.

Related

Android listview item click

I'm trying to get into a listview items have different action when pressed, this action depends on a variable "state", but the problem is that all the items are in the same action, here the code:
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
// Storing JSON item in a Variable
String codigo = c.getString(TAG_CODIGO);
String asignatura = c.getString(TAG_NOMBRE);
int estado = c.getInt("estado");
final int maxhoras = c.getInt("maxhoras");
final String idprogramacion = c.getString("programacionid");
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CODIGO, codigo);
map.put(TAG_NOMBRE, asignatura);
jsonlist.add(map);
list=(ListView)findViewById(R.id.lvclases);
ListAdapter adapter = new SimpleAdapter(Bienvenida.this, jsonlist,
R.layout.listview,
new String[] { TAG_CODIGO,TAG_NOMBRE, }, new int[] {
R.id.codigo, R.id.nombre,
});
list.setAdapter(adapter);
if(estado == 1) {
Log.e("estado", ""+estado);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", idprogramacion);
i.putExtra("maxhoras", maxhoras);
startActivity(i);
/*Toast toast1 = Toast.makeText(getApplicationContext(), "Correcto: el usuario existe", Toast.LENGTH_SHORT);
toast1.show();*/
//Toast.makeText(Bienvenida.this, "You Clicked at " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
}
});
}else{
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
}
});
}
}
I am working on android studio, I appreciate the help
Acually, this is not an answer to your question. But after watching your code it seems that you are not implementing ListView in a correct way.
A simple way to work with ListView goes through following abstract steps:
Make your Collection Ready -> Prepare the Adapter from the collection -> Set this adapter to ListView
In your case, assuming you are calling web services for getting data and your web services is responding with JSON array.
Now, make a POJO(plain old Java object) class like:
public class MyListItem{
private String codigo;
private String asignatura;
private int estado;
private int maxhoras;
private String idprogramacion;
public MyListItem(String codigo, String asignatura, int estado, int maxhoras, String idprogramacion){
this.codigo = codigo;
this.asignatura = asignatura;
this.estado = estado;
this.maxhoras = maxhoras;
this.idprogramacion = idprogramacion;
}
// you can write getter setter methods for this
public int get_estado(){
return estado;
}
public String get_idprogramacion(){
return idprogramacion;
}
public int get_maxhoras(){
return maxhoras;
}
public String get_asignatura(){
return asignatura;
}
}
Now, prepare list like:
ArrayList<MyListItem> mArrayList = new ArrayList<>();
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
mArrayList.Add(
new MyListItem(
c.getString(TAG_CODIGO),
c.getString(TAG_NOMBRE),
c.getInt("estado"),
c.getInt("maxhoras"),
c.getString("programacionid")
)
);
}
Now, you are ready with list, just pass it to your custom adapter. If you are not aware of preparing Custom Adapter, check this link.
Once you are ready with making custom adapter, pass the list to this adapter like:
MyCustomAdapter adapter = new MyCustomAdapter(context, mArrayList);
Note: Above line strictly depends constructor of your custom adapter, say, MyCustomAdapter
After that, you are ready with your adapter, set it to your ListView, like:
list.setAdapter(adapter);
Now, here you set the OnItemClickListener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
MyListItem item = (MyListItem)parent.getItem(position);
if(item.get_estado() == 1)
{
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", item.get_idprogramacion());
i.putExtra("maxhoras", item.get_maxhoras());
startActivity(i);
}
else{
Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + item.get_asignatura(), Toast.LENGTH_SHORT).show();
}
}
});
Hope you get what you are trying to achieve..
This should help you out.
Instead of having two different onClickListeners(), try using only one and move your if-else block inside of the onItemClick() method
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(estado == 1) {
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", idprogramacion);
i.putExtra("maxhoras", maxhoras);
startActivity(i);
} else {
// Do something else
}
}
});
Problem is estado variable, it's global varible, so When you use listview.setOnItemClickListener(...) that mean all the item in listview will be the same action with your above code.
Solution is you should create your own custom adapter and then implement OnItemClickListener in your adapter, base on different states to set different actions for item . Also you can setOnClickListener in getView() in Adapter and base on state also.
Please refer as below :
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int estado = -1;
// you should do something like this
/* ********** */
YourItem item = ((YourItemsData)data).get(position);
estado = item.getState();
/* ********** */
if(estado == 1) {
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", idprogramacion);
i.putExtra("maxhoras", maxhoras);
startActivity(i);
} else {
// Do something else
}
}
});

listView item click event not firing

I am having an issue with using a listview that when I click it nothing is happening. I would like for it when I click the listview item to make a toast so I know it is being clicked. I have been trying/researching for a while and nothing. Would anybody mind taking a look to see if I am missing something I just am overlooking? Many thanks in advance!
Here is my class:
public class MyCar extends Activity {
/**
* Called when the activity is first created.
*/
public ListView mylistView;
String carInfo;
private ArrayAdapter<String> mylistAdapter;
ArrayList<String> arrayListCar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycar);
mylistView = (ListView) findViewById(R.id.listView);
arrayListCar = new ArrayList<String>();
//Just had to remove setting this adapter 2 times. Took out line below to fix.
mylistView.setAdapter(mylistAdapter);
mylistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
carInfo = trySomethin();
fillList();
}
public void fillList() {
String make = "";
String model = "";
String[] pieces = carInfo.split("\"");
make = pieces[3];
model = pieces[7];
ArrayList<String> carList = new ArrayList<String>();
carList.add(make + " " + model);
// Create ArrayAdapter using the car list.
mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList);
mylistView.setAdapter(mylistAdapter);
mylistAdapter.notifyDataSetChanged();
}
}
if you have any elements on listview item change this for them
android:focusable="false"
and if you are changing any elements visibility on runtime you have to handle focus programatically each time you change its visibility.
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});

how to Get the Listview on select item in the spinner

Actually i am developing an application which will implement all CURD operation.
My application consist of spinner,Listview,textbox.
Now what i want is, for updating operation , i need to get the values from the listview by selecting.
I don't know how to display the selected values(from Listview) in the Spinner.
Here is my spinner coding
sppriority = (Spinner) findViewById(R.id.sp_priority);
public void addNewTask(View view) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("priority", sppriority.getSelectedItem().toString());
sppriority.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
Task = adapter.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
and this is Listview on click code:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
lvpriority = (TextView) view.findViewById(R.id.lvpriority);
String vallvpriority = lvpriority.getText().toString();
Intent objIndent5 = new Intent(getApplicationContext(),addinbox.class);
objIndent5.putExtra("lvpriority", vallvpriority);
}
This is how i used which is not working:
**if(animalList.size()!=0) {
sppriority.setText(animalList.get("priority"));
}**
public void editTask(View view) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("priority", sppriority.getSelectedItem().toString());
controller.updateTask(queryValues);
}
Please Help me to get the selected item of listview to spinner.
Thanks in advance.
Here is an outline of a simple way:
1) Have a HashSet which is member of your activity, let us call it selectSet.
//Initialize like this
HashSet<String>selectSet=new HashSet<String>();
2) onItemClick of ListView, add item to selectSet.
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
lvpriority = (TextView) view.findViewById(R.id.lvpriority);
String vallvpriority = lvpriority.getText().toString();
selectSet.add(vallvpriority);
}
3) Create ArrayAdapter<String> spinnerAdapter=new ArrayAdapter<String>(context, resource);
4) Iterate through the HashSet and add items to the spinnerAdapter
for(String priority: selectSet){
spinnerAdapter.add(priority);
}
5) Set the spinnerAdapter to your spinner:
spppriority.setAdapter(spinnerAdapter);

Using Spinner And List Views with setOnItemSelectedListener

I'm supposed to make a task , I have a spinner connected with a String array x , this array contains three values , so I want when clicking any choice of the spinner a specific list view will will give a specific three values and , this is my code :
public class Four extends ActionBarActivity {
String x [] = {"Jordan","Saudi Arabia", "Syria"};
String Jordan[] = {"Amman","Aqaba","Sarqa"};
String Saudi[] = {"Riyadh","Jeddah","Khobar"};
String Syria[] = {"Hems","Halab","Demashk"};
Spinner sp1 ;
ListView lv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.four);
lv1 = (ListView)findViewById(R.id.listView1);
// Jordan List View
ArrayAdapter<String> jor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Jordan);
lv1.setAdapter(jor);
// Saudi Arabia List View
ArrayAdapter<String> saud = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Saudi);
lv1.setAdapter(saud);
// Syria List View
ArrayAdapter<String> syr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Syria);
lv1.setAdapter(syr);
sp1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> a = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , x);
sp1.setAdapter(a);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
The thir parameter of onItemSelected() (int arg2 in your example, but I would suggest you rename them) is the position you selected in the Spinner. So you could implement that method like this:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
if (position == 0)
lv1.setAdapter(jor);
else if (position == 1)
lv1.setAdapter(saud);
else if (position == 1);
lv1.setAdapter(syr);
}
Remember that all the variables involved (lv1, jor, saud, syr) must be defined as final to be used inside the anonymous class, e.g.
final ArrayAdapter<String> jor = ...
final ArrayAdapter<String> saud = ...

setting itemListener of variable number of spinners

int numberofSpinner = TransportResult.Transfers.size();
Spinner spin=null;
for(int i=0;i<numberofSpinner;i++)
{
spin = new Spinner(this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,1);
spinLayout.addView(spin,p);
spin.setId(i);
Transfer transfer = TransportResult.Transfers.get(i);
ArrayList<CharSequence> s = new ArrayList<CharSequence>();
for( Line l : transfer.TransferLine)
{
s.add(l.ShortName+" - "+Helper.FindTransportTypeText(l.LineType));
}
adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item,s);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
}
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if(parent.getId()==0){
System.out.println("spin 1 is called");
String str = (String)parent.getSelectedItem();
}else if(parent.getId()==1){
System.out.println("spin 2 is called");
String str = (String)parent.getSelectedItem();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
If the number of spinner is more than 1, only the last spinner is triggered. For example; i have 3 spinner on screen, when i select the item of first or second spinner, the listener is never triggered. Only the third spinner triggers the listener. How can i solve that?
Thank you
UPDATE
when you use more than one spinner then setid for each spinner spin.setId(int) .and you can check id in OnItemSelected method. Mind that when you set OnitemSelected first time onItemSelected is called.
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if(parent.getId()==1){
System.out.println("spin 1 is called");
String str = (String)parent.getSelectedItem();
}else if(parent.getId()==2){
System.out.println("spin 2 is called");
String str = (String)parent.getSelectedItem();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});

Categories

Resources