Getting item position 0 when clicking an item in ListView

274 Views Asked by At

I am trying to send an item position from a Fragment to an Activity, but I always get invoiceId 0 every time I select an item in listView.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent seperateView = new Intent(rootView.getContext(),SeperateViewForDeliveryList.class);
            seperateView.putExtra("invoiceId", listView.getItemAtPosition(position).toString());
            startActivity(seperateView);
        }
    });
    listView.setAdapter(deliveryListAdapter);
    return rootView;

In activity class

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seperate_view_for_delivery_list);
    invoiceId = getIntent().getExtras().getString("invoiceId");
    Toast.makeText(this, "invoiceID " + invoiceId, Toast.LENGTH_SHORT).show();
}
4

There are 4 best solutions below

2
On

We can also pass integer value in an Intent. Try this:

seperateview.putExtra("invoiceId",listview.getItemAtPosition(position));
getIntent().getIntExtra("invoiceId",0);
3
On

Use this

seperateview.putExtra("invoiceId",String.valueOf(position));
1
On
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        Intent seperateview=new Intent(rootView.getContext(),SeperateViewForDeliveryList.class);
        seperateview.putExtra("invoiceId",parent.getItemAtPosition(position).toString());
        startActivity(seperateview);
    }
});
listview.setAdapter(deliveryListAdapter);
return rootView;

Try this

0
On

getItemAtPosition returns an object of the data associated with the specified position in the list, while position itself is what you want.

Change your code to

seperateView.putExtra("invoiceId", String.valueOf(position));