Search code examples
androidandroid-fragmentsandroid-fragmentactivityandroid-listfragment

OnItemClick how to get text value of clicked item from list view


I want to get the text value of a list item and pass it to an edit text in another fragment when list item is clicked.

Here is my code to get the value and pass it to the other fragment.

    lv_categories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String clickedItem = adapterView.getItemAtPosition(i).toString().trim();
            SM.sendData(clickedItem);
        }
    });

send data method

@Override
public void sendData(String message) {
    String tag = "android:switcher:" + R.id.container + ":" + 1;
    SearchFragment searchFragment = (SearchFragment) getSupportFragmentManager().findFragmentByTag(tag);
    searchFragment.displayReceivedData(message);
}

I am able to receive the data but not as is displayed eg. Instead of receiving the list item "Christmas", I am getting something like "com.example.johndoe.project.Category@fa9dc73"

Also how am I able to change fragments on click?

Any help is greatly appreciated thank you!


Solution

  • I am able to receive the data but not as is displayed eg. Instead of receiving the list item "Christmas", I am getting something like "com.example.johndoe.project.Category@fa9dc73"

    Because adapterView.getItemAtPosition(i) Might Returning you custom Model class not String value

    Try this

    lv_categories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    YourModelClass data = adapterView.getItemAtPosition(i);
    
                    SM.sendData(data.getMessage);
                }
            });