Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView onItemClick

I have a ListView which has data from a parsed JSON. So this is my sample code:

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

    /**
     * parsing JSON...
     * ...
     * ...
     * ...
     */

ListAdapter adapter = new SimpleAdapter(this, myList, R.layout.s_layout, new String[]{NAME, TEXT}, new int[]{R.id.name, R.id.text});
    setListAdapter(adapter);

lv.setOnItemClickListener(new OnItemClickListener(){

        public void onItemClick(AdapterView<?> parent, View view, int position, long id){


            String inName = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String inText = ((TextView) view.findViewById(R.id.text)).getText().toString();


            Intent intent = new Intent(getApplicationContext(), StaffProfileActivity.class);

            intent.putExtra("staff_name", inName);
            intent.putExtra("staff_desc", inText);
            startActivity(intent);
       }
});

My problem is that how can i pass my data to Intent without using

String inName = ((TextView) view.findViewById(R.id.name)).getText().toString(); 

I mean, how to get my data from my ListView and give it to intent?

like image 732
elL Avatar asked Feb 28 '13 08:02

elL


2 Answers

adapter.get(position) will return you a HashMap<String, String> for selected element. And use List<T> definition instead of ArrayList<T>

like image 119
pavko_a Avatar answered Sep 20 '22 22:09

pavko_a


From the documentation

public abstract void onItemClick (AdapterView parent, View view, int position, long id)

Callback method to be invoked when an item in this AdapterView has been clicked. Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item.

so in onItemClick you can retrieve your element :

  HashMap<String, String> elt = myList.getItemAtPosition(position);

and then get inName and inText values from elt.

like image 21
Mouna Cheikhna Avatar answered Sep 21 '22 22:09

Mouna Cheikhna