lundi 20 avril 2015

Unable to set Spinner selection value with object

I have a spinner like this:

 List<Vehicle> vehicles = dataSource.getAllVehicles();
 Spinner spVehicle = (Spinner) dialog.findViewById(R.id.spVehicle);
 SpinnerVehicleAdapter sAdapter = new SpinnerVehicleAdapter(getContext(), R.layout.spinner_textview, vehicles);
 spVehicle.setAdapter(sAdapter);

I want to preselect the dropdown value of the spinner so I THINK I have to preselect it with a matching Vehicle Object, right?

Keep in mind, this is inside of an ArrayAdapter<Oil> where I have access to this:

Oil oilChange;
oilChange.getVehicleId();

So, with that info, I try to set it like this:

Vehicle v = new Vehicle(getContext(), oilChange.getVehicleId());
int spinnerPostion = sAdapter.getPosition(v);
spVehicle.setSelection(spinnerPostion);

Here are supplementary methods: (I believe I have confirmed below code is not the issue.)

public Vehicle(Context mContext, int vehicleId) {

    GasDataSource datasource = new GasDataSource(mContext);
    datasource.open();
    Vehicle vehicle = datasource.createVehicle(vehicleId);

    this.vehicleName = vehicle.getVehicleName();
    this.vehicleYear = vehicle.getVehicleYear();
    this.vehicleModel = vehicle.getVehicleModel();
    this.vehicleMake = vehicle.getVehicleMake();
    this.oilDistance = vehicle.getOilDistance();
    this.drivenDistance = vehicle.getDrivenDistance();

    datasource.close();
}

And then:

public Vehicle createVehicle(long id) {

    if (!database.isOpen()) {
        open();
    }

    Vehicle vehicle = new Vehicle();
    Cursor cursor = database.query(MySQLiteHelper.TABLE_VEHICLE, allVehColumns, MySQLiteHelper.COLUMN_VEHICLE_ID + " = " + id, null, null, null, null);
    while (cursor.moveToNext()) {
        vehicle = cursorToVehicle(cursor);
    }
    // Make sure to close the cursor
    cursor.close();
    return vehicle;
}

Now the spinner dropdown in question uses the property vehicle.vehicleName;

And I have a:

  public String toString() {return getVehicleName(); }

...in my vehicle class as well.

Can this work in my method? Or do I have to match on Strings not Objects?

Also, I do not get a crash, I am simply not able to set selection based on vehicle object provided.

With logging I have confirmed that I am creating the correct object based on the list row. So my SQL is good. But I return -1 in the spinnerPosition.

Aucun commentaire:

Enregistrer un commentaire