Syed Adil
Syed Adil

Reputation: 3

How to get value of a ListView item, populated through FirebaseListAdapter

I have a ListView that I populate using the FirebaseListAdapter. Now I want the OnItemClickListener to show the value of the item clicked (the text displayed on the item) in a Toast.

ListView listView;
ListAdapter listAdapter;

mFirebaseRef = new Firebase("https://<firebase root ref>/posts");
mFirebaseQuery = mFirebaseRef.orderByChild("author_id").equalTo(id); //`id` is a variable defined earlier

listAdapter = new FirebaseListAdapter<Post>(this, Post.class, android.R.layout.simple_list_item_, mFirebaseQuery) {
    @Override
    protected void populateView(View view, Post post) {
        String postTopic = post.getTopic();

        ((TextView) view.findViewById(android.R.id.text1)).setText(postTopic);
    }
};

listView = (ListView) findViewById(R.id.postsList);
listView.setAdapter(listAdapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String topic = String.valueOf(parent.getItemAtPosition(position));

        Toast.makeText(getApplicationContext(), "List Item Value: "+topic, Toast.LENGTH_LONG).show();
    }
});

Instead of returning the text displayed on the item (as is in the case an ArrayAdapter is used), String.valueOf returns some reference to the model class I use - Post.class.
The output is something like this: com.example.android.model.Post@a1e1874

Can anybody tell me how to get the value of the list item in this case?

Upvotes: 0

Views: 1603

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599401

AdapterView.getItemAtPosition() returns a Post object, so:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Post post = (Post)parent.getItemAtPosition(position);

    String topic = post.getTopic();

    Toast.makeText(getApplicationContext(), "List Item Value: "+topic, Toast.LENGTH_LONG).show();
}

Upvotes: 2

Related Questions