-2

When I trying to get item index by below code.

Company company = getDefaultCompany();
companyArrayAdapter.getPosition(company);

I always to get result of -1. I don't understand what's wrong? Because

companyArrayAdapter also have type Company.
private ArrayAdapter<Company> companyArrayAdapter;

Next you can see Company class declaration.

@DatabaseTable(tableName=Company.TABLE_NAME)
public class Company {
    public static final String TABLE_NAME = "company";

    @DatabaseField(id = true, columnName = "id")
    private UUID id;

    @DatabaseField(canBeNull=false)
    private String name;

    @DatabaseField
    private  String address;

    @DatabaseField
    private  String phone;

    @ForeignCollectionField(eager = false)
    private ForeignCollection<Contract> contracts;

    public  Company(){

    }
}
Ali
  • 3,346
  • 4
  • 21
  • 56
Adil
  • 124
  • 7
  • where you have initialized array adapter? edit and post the code of your arrayadapter – Jyoti JK Feb 15 '18 at 06:46
  • Array adapter returns -1 when there is no index found for that object. debug and check what is this method is returning `getDefaultCompany()`. – Archana Feb 15 '18 at 06:46
  • getDefaultCompany() has value. – Adil Feb 15 '18 at 06:47
  • ArrayAdapter initialization in onViewCreated event. – Adil Feb 15 '18 at 06:50
  • could you post your `getDefaultCompany()` code – Rajan Kali Feb 15 '18 at 06:52
  • You've not overridden `equals()` in `Company`, so unless the exact object that `getDefaultCompany()` returns has been added to the collection backing the `Adapter`, `getPosition()` will return `-1`. – Mike M. Feb 15 '18 at 06:52
  • 1
    Thank you very much Mike.M. you're really helped me. public boolean equals(Object obj) { return this.id.equals(((Company)obj).getId()); } – Adil Feb 15 '18 at 06:57
  • No problem. You might want to have a read through this, too: https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java. Also, I think Android Studio has a code generation wizard somewhere that will help you properly create those methods. Cheers! – Mike M. Feb 15 '18 at 07:16

2 Answers2

0

ArrayAdapter uses List.indexOf() method which and it can't compare your custom Company class objects and always returns "Not Found" index (-1).

So you should override getPosition() method int your custom adapter which extends ArrayAdapter:

@Override
public int getPosition(@Nullable Company company) {
    /* here write logic of finding your company in companies list and retur index*/
     return index;
}

P.S If you had snippet of your custom adapter I would give you more detailed answer.

godot
  • 3,422
  • 6
  • 25
  • 42
0

you can iterate through the loop of the list

var list=adapter.your_list

var toMatch=yourObject

for((index,elem) in list.withIndex()){
if(elem.someUniqueProperty == toMatch.someUniqueProperty){
var needed_index=index
}
}
Harsh Agrawal
  • 597
  • 3
  • 12