0

我是Android编程的初学者。我正在尝试使用 JSON 将来自 MySQL 数据库的 ID 标识符放入我的列表视图项目,但我无法使其工作。当我点击一个项目时,它可能应该给出我点击的项目的 ID,但它不起作用,我能得到的只是一个错误。

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;
    }


}
4

2 回答 2

0

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].

于 2013-11-05T23:15:55.783 回答
0

通过调用listView.getId()您请求列表视图 ID,而不是列表视图中的项目

改变

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

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

i是里面的项目位置listviewJSONArray

希望这些信息对您有所帮助

于 2013-11-05T23:43:03.477 回答