简体   繁体   中英

Android ListView OnItemClickListener()

I am a beginner in Android programming. I'm trying to put an ID identifier coming from MySQL database using JSON to my listview items but I can't make it work. When i click on an item it should probably give the id of the item I clicked but it is not working and all I can get is a false.

public class MessagingListFragment extends Fragment {

     private String jsonResult;
     private String url = "http://10.0.2.2/mobile/get_my_ins.php";
     private ListView listView;
     List<NameValuePair> nameValuePairs;

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.messaging_list, container, false);
        listView = (ListView) rootView.findViewById(R.id.listView1);
        accessWebService();
        return rootView;
    }


 // Async Task to access the web
    @SuppressLint("NewApi")
   private class JsonReadTask extends AsyncTask<String, Void, String> {
     @Override
     protected String doInBackground(String... params) {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(url);
      nameValuePairs = new ArrayList<NameValuePair>(2);
      nameValuePairs.add(new BasicNameValuePair("stud_id",MainActivity.user_id)); 
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
      try {
       HttpResponse response = httpclient.execute(httppost);
       jsonResult = inputStreamToString(
       response.getEntity().getContent()).toString();
      }

      catch (ClientProtocolException e) {
       e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
      }
      return null;
     }

     private StringBuilder inputStreamToString(InputStream is) {
      String rLine = "";
      StringBuilder answer = new StringBuilder();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));

      try {
       while ((rLine = rd.readLine()) != null) {
        answer.append(rLine);
       }
      }

      catch (IOException e) {
      }
      return answer;
     }

     @Override
     protected void onPostExecute(String result) {
      ListDrawer();
     }
    }// end async task

    public void accessWebService() {
        try{
     JsonReadTask task = new JsonReadTask();
     // passes values for the urls string array
     task.execute(new String[] { url });
        }catch(Exception e){
         Toast.makeText(getActivity(), e.getMessage().toString() + " 3", Toast.LENGTH_LONG).show();
        }
    }

    // build hash set for list view
    public void ListDrawer() {
     List<Map<String, String>> classList = new ArrayList<Map<String, String>>();

     try {
      JSONObject jsonResponse = new JSONObject(jsonResult);
      JSONArray jsonMainNode = jsonResponse.optJSONArray("recipient");

      for (int i = 0; i < jsonMainNode.length(); i++) {
       JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
       String friend = jsonChildNode.optString("last_name") + ", " + jsonChildNode.optString("first_name");
       String outPut = friend;
       classList.add(createMsgList("recipient", outPut));
      }
     } catch (JSONException e) {
         Toast.makeText(getActivity(), e.getMessage().toString() + " 1", Toast.LENGTH_LONG).show();
    }

     try{
         SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity() , classList,
         android.R.layout.simple_list_item_1, new String[] { "recipient" }, new int[] { android.R.id.text1 });
         listView.setAdapter(simpleAdapter);

         listView.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> a, View v, int i,
                long l) {
            // TODO Auto-generated method stub

         Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();

        }

     });
     }catch(Exception e){
         Toast.makeText(getActivity(), e.getMessage().toString() + " 2", Toast.LENGTH_LONG).show();
     }
    }

    private HashMap<String, String> createMsgList(String name, String subject) {
     HashMap<String, String> friendList = new HashMap<String, String>();
     friendList.put(name, subject);
     return friendList;
    }


}

You are popping up a Toast with listView.getId() as the textual content. This will always give you the ID of the listview that is containing your list items.

If you want to grab the data for the view, you will either need to use the position parameter ( int i in the onItemClick method), or you can try to grab the data from the View v if it is a custom view.

For example, instead of passing in a String array into your adapter, you can keep a reference to the array and find the data you are looking for with myArray[i] .

by calling listView.getId() you requested the listview id not the item inside listview

change

Toast.makeText(getActivity(), listView.getId(), Toast.LENGTH_LONG).show();

to

Toast.makeText(getActivity(), "my id and position = "+i, Toast.LENGTH_LONG).show();

i is the item position inside listview and JSONArray

hope this information helpful to you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM