Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Retrieving Object Name and Position

Hello.

I'll post the code first, then I'll explain-

// Prompts the user for deleting the assignment
    @Override
    public void onItemClicked(View v, int position) {
        mPosition = position;
        mPromptDeleteFragment = new PromptDeleteDialogFragment();
        mPromptDeleteFragment.setListener(mListener2);
        mPromptDeleteFragment.show(getSupportFragmentManager(), PROMPT_FRAGMENT);
    }

    // Prompts the user for creating the assignment
    @Override
    public void createItemClickListener(View v, String string) {
        mListItem = new ListItem();
        mListItem.setAssignment(string);
        mItems.add(mListItem);
        mRecyclerView.scrollToPosition(mItems.size() - 1);
        mListAdapter.notifyDataSetChanged();
        Toast.makeText(MainActivity.this, "\"" + mListItem.getAssignment() + "\"" + " has been created.", Toast.LENGTH_LONG).show();
    }

    // If the user deletes the item
    @Override
    public void confirmDeleteListener(View v) {
        mItems.remove(mPosition);
        mListAdapter.notifyDataSetChanged();
        mPromptDeleteFragment.dismiss();
// I want to create the toast here.
    }

So the scenario here is that I have a RecyclerView that displays a list of ListItem objects, and these objects have a getter that retrieves the name of the object. When the user removes the item from the list (confirmDeleteListener) I want to create a Toast that displays the name of the object, however, I also need to get the position too (the position is an interger). How would I get the ListItem from the position if they're two different object types?

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

Hi Diego - Wouldn't mItems.get(mPosition) give you the object?

It would get me the position, but I also need to get the object.

Kourosh Raeen
Kourosh Raeen
23,733 Points

But doesn't mItem contain objects of type ListItem?

I just found a fix:

mListItem = mItems.get(mPosition);
Toast.makeText(MainActivity.this, "\"" + mListItem.getAssignment() + "\"" + " has been removed.", Toast.LENGTH_LONG).show();

Thanks anyway!