passing the position from listview to new activity

怎甘沉沦 提交于 2019-12-24 10:57:13

问题


how can i pass the value or the position of the selected item in listview to a new activity tha will use that value to retrieve data from database in listview (in the new activity)

i have code that it works but always pass a null value for the position that has been passed.

my code for the first activity :

 listView.setOnItemClickListener(new OnItemClickListener() {

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

           // ListView Clicked item index
           int itemPosition     = position;

           // ListView Clicked item value
           String  itemValue    = (String) listView.getItemAtPosition(position);

            // Show Alert HERE THE VALUE IS CORRECT-----
      //     Toast.makeText(getApplicationContext(),
      //        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
      //      .show();
            Intent myIntent = new Intent(view.getContext(), ShowWhereToGo1.class); 
            myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            myIntent.putExtra("id", itemPosition);
            startActivityForResult(myIntent, 0);

          }

     }); 

The second activity:

         Bundle extras = getIntent().getExtras();

      String temp = extras.getString("id");
      Toast.makeText(getApplicationContext(),
                      "Position :"+temp , Toast.LENGTH_LONG)
                      .show();
     }

also i tried in the second activity that code but still pass null value:

   Intent in = this.getIntent();
    String name = in.getStringExtra("id");

            Toast.makeText(getApplicationContext(),
            "Position :"+name , Toast.LENGTH_LONG)
            .show();

Is there any other way to pass and retrieve the values between activities?


回答1:


use

  Bundle extras = getIntent().getExtras();
  if (extras != null) 
  String temp = extras.getInt("id");

instead of extras.getString("id") because you are passing Integer from ListView click



来源:https://stackoverflow.com/questions/19565957/passing-the-position-from-listview-to-new-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!