0

I am trying to retrieve the selected item of a ListView when user clicks a button. I am using the below code in setOnItemClickListener:

lvequipments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            Object o = lvequipments.getItemAtPosition(i);
            CustomerEquipmentView customerEquipmentView = (CustomerEquipmentView)o;
            Product product = workOrderPresenter.getCustomerModel().getProduct(customerEquipmentView);

            Toast.makeText(getBaseContext(), customerEquipmentView.getModelName(), Toast.LENGTH_LONG).show();

        }
    });

And the toast is successfully getting the model name from the object when I select different items in the ListView. Outside the ListView I have a button that saves some data from a different panel. I am attempting to retrieve the ListView item again here like so

public void saveToDatabase() {
        Object o = lvequipments.getSelectedItem();
        CustomerEquipmentView customerEquipmentView = (CustomerEquipmentView)o;
        ...
}

But o is null. Evaluating lvequipments.getSelectedItem() at a breakpoint during run also gives null. How do I successfully retrieve the selected item from the ListView from outside the onItemClick() method?

Nick Friskel
  • 2,369
  • 2
  • 20
  • 33
wizloc
  • 2,202
  • 4
  • 28
  • 54

1 Answers1

1
  1. define an int field in class, like int SelectedItemIndex
  2. in onItemSelected(...) method write SelectedItemIndex = i
  3. in savetodatabase method get the selected element by lvequipments.getItemAtPosition(SelectedItemIndex); that what you want i think
Mean Coder
  • 304
  • 1
  • 12
  • Is this the only way? Why doesn't getSelectedItem() work, it seems like that should be a painless way to retrieve selected item – wizloc Dec 21 '16 at 20:21
  • I am still new to android so I am not sure exact differences between two handlers, but referring to this answer http://stackoverflow.com/questions/26399757/android-listview-get-the-selected-item he says onItemClick is better for tablet. At any rate your answer is working for me – wizloc Dec 21 '16 at 20:35