0

I want to set the selected item of a spinner :

adapter = new ArrayAdapter<Rue>(this, android.R.layout.simple_spinner_item, db.getAllRues()); // db.getAllRues() has data
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ruePpale.setAdapter(adapter);
ruePpale.setSelection(adapter.getPosition(db.getRue(p.getDec_decoup_terri_code())), true); // p.getDec_decoup_terri_code() has data

Code of db.getRue :

public Rue getRue(String decoup_terri_code) {
    Rue r = new Rue();
    String[] columns = {"decoup_terri_code","decoup_terri_nom"};
    Cursor c = bd.query(T_DECOUP_TERRIT, columns, "decoup_terri_code=?", new String[]{decoup_terri_code}, null, null, null);
    if (c != null && c.getCount() > 0 ) {
        c.moveToFirst();
        r.setDecoup_terri_code(c.getString(0));
        r.setDecoup_terri_nom(c.getString(1));
    }
    return r;
}

The problem is that at runtime the spinner does not scroll automatically to the desired item ! What is bad in my code ?

-- EDIT --

I overwrote the equals method in the class Rue :

@Override
public boolean equals(Object o) {
    if (!(o instanceof Rue)) {
        return false;
    }
    Rue comp = (Rue) o;
    return (this.getDecoup_terri_code() == comp.getDecoup_terri_code() && this.getDecoup_terri_nom() == comp.getDecoup_terri_nom());
}

But the spinner does not select the item !

pheromix
  • 18,213
  • 29
  • 88
  • 158
  • did you tried to debug your code? what returns `adapter.getPosition()` ? ... I'm pretty sure that -1 ... your item cannot be find with `List.indexOf(item)` ... – Selvin Apr 01 '15 at 13:42
  • yes it is -1 , so what is wrong ? – pheromix Apr 01 '15 at 13:49
  • basic java conception ... -1 means [object was not found](http://developer.android.com/reference/java/util/List.html#indexOf(java.lang.Object)) ... obviously [`List.indexOf`](https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/ArrayAdapter.java#L347) doesn't know how to compare(find equal) your objects – Selvin Apr 01 '15 at 13:54
  • So I should inherit ArrayAdapter and implement the methods getCount , getPosition and getItem ? – pheromix Apr 01 '15 at 14:06
  • no, java basics: override `equals` method in `Rue` class – Selvin Apr 01 '15 at 14:08
  • check speciall things like other object is null or different class , return thisRueObject is equal otherRueObject (there is pleanty examples over the internet) – Selvin Apr 01 '15 at 14:24
  • another java's basics: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Selvin Apr 01 '15 at 14:37
  • it wasn't my answer ... it was you with a little help :) – Selvin Apr 01 '15 at 14:44

1 Answers1

0

Ok , from the help of @Selvin I implemented the equals method which I posted in my question. And I replaced the == comparator to the equals method.

pheromix
  • 18,213
  • 29
  • 88
  • 158