将位置从listview传递到新活动 [英] passing the position from listview to new activity

查看:90
本文介绍了将位置从listview传递到新活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将列表视图中所选项目的值或位置传递给新活动,tha将使用该值从列表视图中的数据库中检索数据(在新活动中)

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.

我的第一个活动代码:

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

          }

     }); 

第二项活动:

         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?

推荐答案

使用

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

而不是extras.getString("id"),因为要从ListView传递Integer,请单击

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

这篇关于将位置从listview传递到新活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆