androidjsononitemclicklisteneronitemclick

Can't get the right id into the Fragment


I need to transfer the value of id parsed from JSON entity by row click ex.(first item in the listview has id of 861(which is gotten from JSON) second one 823, I need to transfer the right id to the FrafmentB

This is how I'm getting the id:

List<NameValuePair> param = new ArrayList<NameValuePair>();
 JSONObject json = jsonParser.makeHttpRequest(URL_MESSAGES, "GET", param, token);
 JSONObject data = json.getJSONObject("data");
 JSONArray messages = data.getJSONArray("messages");
for(int i=0;i<messages.length();i++){
JSONObject c = messages.getJSONObject(i);
read_status=c.getString(TAG_READ_STATUS);
if(read_status.equals("unread")){
msgID=c.getInt("id");
Log.d("BUNDLE ID", String.valueOf(msgID));
title = c.getString(TAG_TITLE);
Log.d("TITLE",title);
time=c.getString(TAG_TIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_TIME, time);

mailList.add(map);

This is the way I transfer the id into fragment

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fm=getFragmentManager();
FragmentTransaction transaction=fm.beginTransaction();
bundle.putInt("message", msgID );
MessageView ViewMessages=new MessageView();
ViewMessages.setArguments(bundle);
transaction.replace(R.id.fragmentInnerMail,ViewMessages);
transaction.commit();
}

When the user clicks on item from the row , only the last id(which is parsed via asyncTask) goes into fragmentB, not an id based on the row from listview, I can't figure it out.

Adapter

  @Override
        protected void onPostExecute(String s) {
            ListView list = (ListView) getActivity().findViewById(R.id.list);
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), mailList,
                    R.layout.mail_row, new String[] { TAG_TITLE,
                    TAG_TIME}, new int[] {
                    R.id.mTitle,R.id.mDate});

            list.setAdapter(adapter);


            pDialog.dismiss();

        }

Solution

  • You need to add the id to your HashMap

    map.put(TAG_ID, msgID);
    

    and onItemClick you can get the item you pressed on this way:

    HashMap<String, String> itemAtPostion =  parent.getItemAtPosition(position);
    

    and then

       bundle.putInt("message", itemAtPostion.get(TAG_ID) );