adapter.getPosition返回-1

时间:2017-08-19 13:42:15

标签: java android

“此代码适用于字符串ID小于20但大于1000的字符串返回-1。” “--- MySpinner.setSelection(adapter.getPosition(new CustomSpinnerList(String.valueOf(id),name))); // Sample id =”1254“,name =”Aaaaa aaa“ -------------------------------------------------- -------

private void setADivisions(int divisional_id) {
    DatabaseHelper myDb= new DatabaseHelper(this);
    ArrayList<CustomSpinnerList> MyArrList = new ArrayList<>();
    Spinner MySpinner = (Spinner)findViewById (R.id.spinnerDivision);
    List<SysDivisionTable> 

MyList=myDb.get_all(Integer.valueOf(divisional_id));
        int id=0;
        String name="";
        myDb.closeDB();
        for(SysDivisionTable MyTable:MyList) {
            if(MyTable.Get_col_A_division_id()==current_Adiv_id) { 
                id=MyTable.Get_col_A_division_id();//="1245"
                name=MyTable.Get_col_A_division_name();="Aaaaa aaa"
            }
            MyArrList.add(new CustomSpinnerList(String.valueOf(MyTable.Get_col_A_division_id()), MyTable.Get_col_A_division_name()));
        }

    ArrayAdapter<CustomSpinnerList> adapter = new ArrayAdapter<CustomSpinnerList>(this, android.R.layout.simple_spinner_dropdown_item, MyArrList);
    Log.d("D01", "adapter.String.valueOf(id) "+ String.valueOf(id)+ " *** "+name);
    Log.d("D02", "adapter.getPosition"+ adapter.getPosition(new CustomSpinnerList(String.valueOf(id), name)));

    MySpinner.setAdapter(adapter);
    MySpinner.setSelection(adapter.getPosition(new CustomSpinnerList(String.valueOf(id), name)));// Sample    id="1254",name="Aaaaa aaa"
}



    public class CustomSpinnerList {
        private String id; 
        private String name;

        public CustomSpinnerList(String id, String name) {
            this.id = id;
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return name;
        }
        @Override
        public boolean equals(Object obj) {
            if(obj instanceof CustomSpinnerList){
                CustomSpinnerList c = (CustomSpinnerList)obj;
                if(c.getName().equals(name) && c.getId()==id ) return true;
            }
            return false;
        }
    }

1 个答案:

答案 0 :(得分:0)

==(地址比较)替换为equals()(值比较)

        @Override
        public boolean equals(Object obj) {
            if(obj instanceof CustomSpinnerList){
                CustomSpinnerList c = (CustomSpinnerList)obj;
                if(c.getName().equals(name) && c.getId().equals(id) ) return true;
            }
            return false;
        }