如何在Android Listview中获取所选列表项的值

时间:2018-08-08 09:53:44

标签: android listview

我正在尝试获取选定列表项在android中的onClick的值,

为此,我一直在使用以下代码进行json解析,当选择列表项时,我尝试获取其值,但得到的结果如下:{name = supriya},所需结果为'supriya',如何实现这个,请帮忙。

public class Popup extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
public ListView lv;
String name;
String path;
String dtype;
String video;
String audio;
String item;
String interactivity;

//private static String url = "http://10.60.100.101/mydata/chapter.php";
private static String url;
ArrayList<HashMap<String, String>> contactList;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.popup);
    contactList = new ArrayList<>();
    //Button bt= (Button)findViewById(R.id.next);
    lv = (ListView) findViewById(R.id.list);

    //Receiving content from the Mygrid.java page
    Intent intent = getIntent();
    item = intent.getStringExtra("name");
    System.out.println("Item clicked at the previous activity"+ item);
    getSupportActionBar().setTitle(item);

    new GetContacts().execute();

}


private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Popup.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        //...code for bypassing the ssl security..

        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }
        };
       try {
       // Install the all-trusting trust manager
         SSLContext sc = SSLContext.getInstance("SSL");
         sc.init(null, trustAllCerts, new java.security.SecureRandom());
         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }

          catch(Exception e){
                 System.out.println("supriya di error"+ e);
           }
             // Create all-trusting host name verifier
                  HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
                   }
        };

             // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        //.....code of bypassing certificate ends here


        // String url= "http://www.ebiebook.com/rest/DRMRestServices.svc/rest/products";
       // url = "http://10.60.100.101/mydata/chapter.php";

        // Making a request to url and getting response
        url = "https://stage.indiannicalearning.com/mydata/";

        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);


        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                // Getting JSON Array node

                JSONArray contacts = jsonObj.getJSONArray("supi");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    name = c.getString("topics");
                    path = c.getString("url");
                    dtype = c.getString("type");
                    //String email = c.getString("email");
                    System.out.println("name value :"+name);
                    System.out.println("url value :"+path);
                    System.out.println("data type value :"+dtype);
                    // tmp hash map for single contact

                     HashMap<String, String> contact = new HashMap<>();
                    // adding each child node to HashMap key => value
                    System.out.println("contact name value :"+name);
                    //System.out.println("contact url value :"+url);
                    System.out.println("contact data type value :"+dtype);
                    contact.put("name", name);
                    //contact.put("url", url);
                   // contact.put("dtype", dtype);
                    // adding contact to contact list
                    contactList.add(contact);
                }
                }


                catch(Exception e)
                { System.out.println("error"+ e);}
                } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });
            }
            return null;
    }

   @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

           final ListAdapter adapter = new SimpleAdapter(Popup.this, contactList, R.layout.list_item,
                   new String []{"name"}, new int[]{R.id.name});

                   lv.setAdapter(adapter);
                   lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view,
                                   int position, long id) {

               String text =parent.getItemAtPosition(position).toString();

                     //  String text = ((TextView) view).getText().toString();
                    // Toast.makeText(getApplicationContext(),arr[position],Toast.LENGTH_LONG).show();
                   System.out.println("pop up  page text:" +text);
                   System.out.println("pop up  page path:" +path);

                   Intent intent = new Intent(Popup.this, AudioPlayer.class);
                   intent.putExtra("path", path);
                   intent.putExtra("name", text);
                   startActivity(intent);
            }
       });
    }
}
}

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试一下

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
                                       int position, long id) {

      HashMap<String, String> contact=(HashMap<String, String>)parent.getItemAtPosition(position).toString()
      String text =contact.get("name");


      System.out.println("pop up  page text:" +text);
      System.out.println("pop up  page path:" +path);

      Intent intent = new Intent(Popup.this, AudioPlayer.class);
      intent.putExtra("path", path);
      intent.putExtra("name", text);
      startActivity(intent);
   }
});