Alabhya
Alabhya

Reputation: 490

Wrong item selected in list

I have a ListActivity with SimpleAdapter to display a 2 item list using the simple_items_list_2 layout. An ArrayList of HashMap holds the items.

The list has to hold data i receive as UDP packets from different. So, I have another thread, in which these packets are received. From there, using a handler, it sends the received data, and adds the items to the list.

Now I receive the packets properly, even the list is generated. However, when i select say item B, it selects item A sometimes.

Here are the code snippets:

In the OnCreate() ,

        lv = getListView();

        list = new ArrayList<HashMap<String, String>>();

        String[] from = { "name", "address" };
        int[] to = { android.R.id.text1, android.R.id.text2 };

        adapter = new SimpleAdapter(getApplicationContext(), list,
                android.R.layout.simple_list_item_2, from, to);
        setListAdapter(adapter);

In the handler's code after it gets a message with the contents from the thread :

        list.add(putData(scanned_name, scanned_addr));
        adapter.notifyDataSetChanged();
            lv.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) { 

                TextView name_tv = (TextView) findViewById(android.R.id.text1);
                TextView addr_tv = (TextView) findViewById(android.R.id.text2);

                selectedName = name_tv.getText().toString();
                selectedAddr = addr_tv.getText().toString();

The HashMap function to put data:

private HashMap<String, String> putData(String name, String address) {
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("name", name);
        item.put("address", address);
        return item;
    }

Any help?

Upvotes: 0

Views: 116

Answers (1)

waqaslam
waqaslam

Reputation: 68177

I think you need to use view.findViewById

TextView name_tv = (TextView) view.findViewById(android.R.id.text1);
TextView addr_tv = (TextView) view.findViewById(android.R.id.text2);

Upvotes: 2

Related Questions