[英]getting the id from the listview when click on item , in another activity
The code below give generate the ListView 下面的代码生成ListView
public class MyList extends ListActivity {
static final String[] COUNTRIES = new String[] {LONG LIST OF COUNTRIES};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,R.layout.main,COUNTRIES));
ListView lv=getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View view,int position,long id){
Intent i=new Intent(MyList.this,Another.class);
Bundle b = new Bundle();
b.putInt("id", (int)id);
intent.putExtras(b);
startActivity(intent);
}
});
}
}
Another activity is 另一项活动是
public class Another extends Activity{
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mainseocnd);
Bundle b=new Bundle();
int value= b.getInt("id",0);
TextView tv=(TextView)findViewById(R.id.text);
tv.setText(""+value);
}
}
Now when i click on the any list item say id-5 it always display 0 I want to get the listview item id like if user click second item in list the another acivity should display 1(b/c start with 0). 现在当我点击任何列表项时说id-5它总是显示0我想获得listview项ID如果用户单击列表中的第二项,则另一个acivity应该显示1(b / c以0开头)。 please correct me where it is going wrong.
请纠正我哪里出错了。 Thanks in advance!!
提前致谢!!
In second activity instead of 在第二次活动而不是
Bundle b=new Bundle();
int value= b.getInt("id",0);
use 采用
int value = icicle.getInt("id",0);
This will give you a solution... :) 这会给你一个解决方案...... :)
Your way of retrieving the value is wrong: 您检索值的方法是错误的:
Bundle b=new Bundle();
int value= b.getInt("id",0);
You create a new bundle and try to get a value from it, when there is none (it's new) . 当没有(它是新的)时,你创建一个新的bundle并尝试从中获取一个值。 You have to get the extras supplied with the launch intent for that activity instead.
您必须获得随该活动的启动意图提供的额外内容。 Try
尝试
int value = getIntent().getIntExtra("id", 0);
instead. 代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.