如何使用onItemClick将特定值传递给新活动

时间:2014-06-11 16:54:10

标签: android json listview

我使用myIntent.putExtra(“name”,)尝试了各种不同的方法;没有什么可以检索我在列表视图中单击的项目的“TAG_NAME”。它会在没有问题的情况下打开新活动,但传递的值为null。第二个活动几乎与这个活动相同,所以我也不会放置它。唯一的区别是我声明了多少个json节点,以及我想根据我从主活动中获取的类别名称使用开关的事实。因此,根据点击的内容,json将使用不同的URL作为数据。

我需要帮助确定如何传递按下的类别名称(TAG_NAME)。

编辑:快速注释 - 下面的代码可以很好地显示列表视图,其中包含网址中提供的数据。此外,当点击并且不使用传递的数据(并且始终为空),但是静态URL时,第二个活动的代码也像魅力一样。我唯一的问题是传递的变量。

 public class Main_activity extends ListActivity {


  //URL to get JSON Array
  private static String url = "http://localhost/category";
  //JSON Node Names
  private static final String CAT ="categories";
  private static final String TAG_NAME = "name"; //copy-paste to other same static string variables
  JSONArray categories  = null;
  private ArrayList<HashMap<String, String>> oslist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        oslist = new ArrayList<HashMap<String, String>>();
        new JSONParse().execute();


    ListView lv = getListView();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
            Intent myIntent = new Intent(view.getContext(), happy_products.class); 
            startActivityForResult(myIntent,0);
            // display happy_products.class     
        }
       });
     }


    private class JSONParse extends AsyncTask<Void, Void, Void> {
       private ProgressDialog pDialog;
      @Override
      protected void onPreExecute() {
          super.onPreExecute();
          // Showing progress dialog
          pDialog = new ProgressDialog(Main_happy.this);
          pDialog.setMessage("Please wait...");
          pDialog.setCancelable(false);
          pDialog.show();
      }
      @Override
        protected Void doInBackground(Void... args) {
        // Creating service handler class instance
          ServiceHandler sh = new ServiceHandler();

          // Making a request to url and getting response
          String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

          Log.d("Response: ", "> " + jsonStr);

          if (jsonStr != null) {
              try {
        // Getting JSON from URL
             JSONObject jsonObj = new JSONObject(jsonStr);
              categories = jsonObj.getJSONArray(CAT);
            for(int i = 0; i < categories.length(); i++){
            JSONObject c = categories.getJSONObject(i);

            // Storing  JSON item in a Variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            // Adding value HashMap key => value
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(TAG_NAME, name);
            oslist.add(map);
              }
             } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
     }
      @Override
      protected void onPostExecute(Void r) {
          super.onPostExecute(r);
          // Dismiss the progress dialog
          if (pDialog.isShowing())
              pDialog.dismiss();
          /**
           * Updating parsed JSON data into ListView
           * */
          ListAdapter adapter = new SimpleAdapter(Main_happy.this, oslist,
                  R.layout.category_list,
                  new String[] {TAG_ID, TAG_NAME,TAG_UPDATE}, new int[] {R.id.id,R.id.name, R.id.lastUpdated});
          setListAdapter(adapter);
      }

    }
}

编辑回应第一条评论:

我可能没有使用正确的密钥。该错误与返回的null值有关,因此doInBackground无法获取数据,因为url为null。 “

HashMap<String,String> map =(HashMap<String,String>)lv.getItemAtPosition(position);
            String value = map.get(TAG_NAME);

 06-11 13:10:24.191: E/AndroidRuntime(2173): java.lang.RuntimeException: An error occured while executing doInBackground()
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.lang.Thread.run(Thread.java:841)
    06-11 13:10:24.191: E/AndroidRuntime(2173): Caused by: java.lang.NullPointerException
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.net.URI.parseURI(URI.java:353)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.net.URI.<init>(URI.java:204)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.net.URI.create(URI.java:725)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at apphap.ServiceHandler.makeServiceCall(ServiceHandler.java:68)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at apphap.ServiceHandler.makeServiceCall(ServiceHandler.java:34)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at apphap._products$JSONParse.doInBackground(_products.java:76)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at apphap._products$JSONParse.doInBackground(_products.java:1)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
    06-11 13:10:24.191: E/AndroidRuntime(2173):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)

1 个答案:

答案 0 :(得分:0)

散列图未正确声明(本地而不是全局)并导致传递的值为null,因此出现错误。

确实是一个菜鸟的错误,但它现在已经解决了。只是我的不当声明。 :\

感谢你的帮助,以及帮助我​​(@Raghunandan)的尝试。