【问题标题】:Get details of an item clicked in a listview in next activity获取在下一个活动的列表视图中单击的项目的详细信息
【发布时间】:2016-05-01 20:34:12
【问题描述】:

您好,我正在编写一个代码,它在列表视图中显示一些详细信息,例如名称和价格,这些信息来自 MySQL 数据库。现在,当我想单击该列表视图中的那个特定项目时,我想要的是我想移动到布局相同的下一个活动,只有当单击一个项目时数据会不断变化。

就像当我点击名字 A 时,我想打开一个新的活动,其中的名字以及它的地址密码,电话号码将详细显示。

我已在 lsitview 中获取了所有详细信息,并在其中显示了一些我想要的内容,然后将下一个传递给详细活动。 但我在下一个活动中没有得到任何价值。 请看我写的代码。

带有列表视图的活动

public class Plumbers extends Activity {
    String myJSON;

    public static final String TAG_RESULTS="result";
    public static final String TAG_NAME = "Name";
    public static final String TAG_ADDRESS = "Address";
    public static final String TAG_PINCODE = "Pincode";
    public static final String TAG_PHONENUMBER = "Phone_Number";
    public static final String TAG_DOB = "DOB";
    public static final String TAG_AADHARNUMBER = "Aadhar_Number";
    public static final String TAG_Price = "price";
    public static final String TAG_Spl = "spl";

    JSONArray peoples = null;
    ArrayList<HashMap<String, String>> personList;

    ListView list;
    EditText search;
    Spinner spin;

    protected Object adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        list = (ListView) findViewById(R.id.list1);
        spin=(Spinner)findViewById(R.id.spinner1);
        search = (EditText)findViewById(R.id.search);
        personList = new ArrayList<HashMap<String,String>>();
        getData();
    }

    protected void showList(){
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray(TAG_RESULTS);

            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);

                String Name = c.getString(TAG_NAME);
                String price = c.getString(TAG_Price);
                String spl = c.getString(TAG_Spl);

                HashMap<String,String> plumbers = new HashMap<String,String>();
                plumbers.put(TAG_NAME,Name);
                plumbers.put(TAG_Price,price);
                plumbers.put(TAG_Spl,spl);

                personList.add(plumbers);
            }

            final ListAdapter adapter = new SimpleAdapter(
                    Plumbers.this, personList, R.layout.plumber,
                    new String[]{TAG_NAME ,TAG_Spl,TAG_Price },
                    new int[]{R.id.Name , R.id.spl ,R.id.price}
            );

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

                    Intent intent = new Intent(Plumbers.this, Plumber1.class);
                    intent.putExtra("Name", TAG_NAME);
                    intent.putExtra("Address", TAG_ADDRESS);
                    intent.putExtra("Pincode", TAG_PINCODE);
                    intent.putExtra("Phone_Number", TAG_PHONENUMBER);

                    startActivity(intent);
                }
            });

            spin.setAdapter((SpinnerAdapter) adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new   BasicHttpParams());
                HttpPost httppost = new HttpPost("http://192.168.2.7/homerun/plumbers.php");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;
                showList();
            }
        }

        GetDataJSON g = new GetDataJSON();
        g.execute();
    }
}

活动的下一个项目的详细信息

public class Plumber1 extends Activity { 
    ImageView img,call;
    TextView pl1,nm,ad,phn,qu,pin;
    String  Name,Address,Pincode,Phone_Number;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plumber1);
        img=(ImageView)findViewById(R.id.imag);
        call=(ImageView)findViewById(R.id.call);
        pl1=(TextView)findViewById(R.id.pl1);
        nm=(TextView)findViewById(R.id.name);
        ad=(TextView)findViewById(R.id.Address);
        pin=(TextView)findViewById(R.id.Pincode);
        phn=(TextView)findViewById(R.id.phn);
        qu=(TextView)findViewById(R.id.quotation);

        Intent intent = getIntent();
        if (intent.getExtras() != null) {

        Name = intent.getStringExtra("Name");
         Address = intent.getStringExtra("Address");
         Pincode = intent.getStringExtra("Pincode");
         Phone_Number = intent.getStringExtra("Phone_Number");
           Toast.makeText(getApplicationContext(),  Name + "" + Address + "" + Pincode + "" + Phone_Number +"" ,  Toast.LENGTH_LONG).show();
    }

        nm.setText(Name+"");
    ad.setText(Address+"");
    pin.setText(Pincode+"");
    phn.setText(Phone_Number+"");
        call.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Intent in = new Intent(android.content.Intent.ACTION_DIAL, Uri
                        .parse("tel:+918058706096"));
                startActivity(in);
            }
        });
    }
}

php文件

<?php
    mysql_connect("localhost","root","");  
    mysql_select_db("homerun");  
    $sql="select * from plumbers WHERE Status = '1'  GROUP BY price  ORDER BY  name ASC" ;  
    $res = mysql_query($sql);
    $result = array();
    while($row = mysql_fetch_array($res)){
        array_push($result,
        array('Name'=>$row[1],'spl'=>$row[8],'price'=>$row[7]));
    }

    echo json_encode(array("result"=>$result));

    mysql_close();
?>

【问题讨论】:

    标签: android listview android-intent


    【解决方案1】:

    你做错了一件事。当您传递意图时,您只是给出了 2 个常量,而不是您想要传递的实际值。

    intent.putExtra("Name", TAG_NAME);
    intent.putExtra("Address", TAG_ADDRESS);
    intent.putExtra("Pincode", TAG_PINCODE);
    intent.putExtra("Phone_Number", TAG_PHONENUMBER);
    

    这应该是这样的:

    MyObject myObj = adapter.getItem(position);
    Intent intent = new Intent(Plumbers.this, Plumber1.class);
    intent.putExtra(TAG_NAME, myObj.getName());
    intent.putExtra(TAG_ADDRESS, myObj.getAdress());
    intent.putExtra(TAG_PINCODE, myObj.getPinCode());
    intent.putExtra(TAG_PHONENUMBER, myObj.getPhoneNumber());
    

    在你的第二个活动中:

    String name = intent.getStringExtra(TAG_NAME);
    String adress = intent.getStringExtra(TAG_ADRESS);
    String pincode = intent.getStringExtra(TAG_PINCODE);
    String phonenumber = intent.getStringExtra(TAG_PHONENUMBER);
    

    基本上 atm 您传递的是 2 个常量,而不是所选对象的实际信息。例如,这里:

     intent.putExtra("Name", TAG_NAME);
    

    您正在传递一个用键“名称”标识的字符串,它的内容被定义为这样的静态。这是错误的。

     public static final String TAG_NAME = "Name";
    

    所以基本上你是从

     String name = intent.getStringExtra(TAG_NAME);
    

    希望我能理解自己。

    【讨论】:

      【解决方案2】:

      这是你在第二个活动中应该做的事情

       String  Name = intent.getStringExtra("Name");
              TAG_ADDRESS = intent.getStringExtra("Address");
              TAG_PINCODE = intent.getStringExtra("Pincode");
              TAG_PHONENUMBER = intent.getStringExtra("phone_number");
      

      你必须使用变量值而不是变量名 例如,如果您的密钥是 String TAG_ADDRESS="myKey" 在第二个活动中,您必须使用 myKey 而不是 TAG_ADDRESS

      【讨论】:

      • 感谢您的回复...我已经根据您所说的更改了代码,但现在我只得到密钥,无论是在 settext 还是在 toast 中。没有获得任何值..在问的问题中编辑了更改的代码..请帮助
      【解决方案3】:

      我相信您在额外检索意图时使用了值而不是键。例如,而不是:-

      intent.putExtra("Name", TAG_NAME);
      ...
      String  Name = intent.getStringExtra("TAG_NAME");
      

      你应该有:-

      intent.putExtra("Name", TAG_NAME);
      ...
      String  Name = intent.getStringExtra("Name");
      

      即设置/放置intent extra时第一个参数是key(变量名),第二个参数是value。检索时,您要求 key 并获得/返回 value

      回应评论:-

      感谢您的回复...我已根据您的内容更改了代码 说过,但现在我只得到钥匙,无论是在 settext 还是在 吐司。没有获得任何值..更改的代码在 问的问题..请帮忙:)


      我认为您在将它们用于 JSON 和 INTENTS 时会混淆键/值。

      例如,你这样做:-

      public static final String TAG_NAME = "Name";
      

      TAG_NAME 将始终具有 Name 值(不是来自 DB/JSON 的名称)。

      稍后你会这样做:-

      intent.putExtra("Name", TAG_NAME);
      

      因此,带有名为 Name 的键的 Intent extra 将被设置为 TAG_NAME 的值,这相当于将值设置为 Name >

      您可以使用(其中 name 是根据 String Name = c.getString(TAG_NAME); 从 DB/JSON 中提取的名称):-

      intent.putExtra("Name", name); 
      

      或(因为 TAG_NAME 等同于 名称

      intent.putExtra(TAG_NAME, name);
      

      【讨论】:

      • 感谢您的回复...我已经根据您所说的更改了代码,但现在我只得到密钥,无论是在 settext 还是在 toast 中。未获得任何值..在询问的问题中编辑了更改的代码..请帮助:)
      • 在构建列表之前将值保存到 Hashmap 时,可能会覆盖已设置的初始值。我建议创建一个简单的 PlumberEmployee POJO 并将 Hashmap 键值设置为 Name-PlumberEmployee
      • 我开始做的是创建具有明确名称(恕我直言)的字符串资源并将它们用作键,例如:intent.putExtra(getResources().getString(R.string.intentkey_activitycaller), THIS_ACTIVITY + "_ADD");,在这种情况下,R.string.intentkey 定义为&lt;string name="intentkey_activitycaller"&gt;CALLER&lt;/string&gt;。冗长但可以避免混淆/错误输入问题。在这种情况下,THIS_ACTIVITY + "_ADD" 是存储在 Intent extra 中的值,键为 CALLER。检索为caller = getIntent().getStringExtra(getResources().getString(R.string.intentkey_activitycaller));
      【解决方案4】:

      您可以通过两种方式在另一个活动中获取数据,首先是使用共享偏好存储您在共享偏好中选择的数据,然后使用 setter 和 getter 在下一个活动中获取数据。 2.您可以使用意图传递数据 假设我想使用意图传递可能的名称,所以我将使用密钥在下一个活动中获取它,例如。

      意图 i=new(this,nextactivity.class);

      i.putstring("name","tanmeet");

      现在使用捆绑包在下一个活动中恢复它

      捆绑附加服务 = getIntent().getExtras();

          String myName= extras.getString("name");
      

      这里的名字是我的钥匙

      【讨论】:

      • 而不是使用这个“Intent intent = getIntent();”使用 Bundle 来获取像这样的值 Bundle extras = getIntent().getExtras(); String myName= extras.getString("name");如果觉得有用请点赞
      【解决方案5】:

      只需更改 onItemClickListener() 代码即可。

      list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
      
                      Intent intent = new Intent(Plumbers.this, Plumber1.class);
                      intent.putExtra("Name", personList.get(position).get(TAG_NAME));
                      intent.putExtra("Address", personList.get(position).get(TAG_ADDRESS));
                      intent.putExtra("Pincode", personList.get(position).get(TAG_PINCODE));
                      intent.putExtra("Phone_Number", personList.get(position).get(TAG_PHONENUMBER));
      
                      startActivity(intent);
                  }
              });
      

      但是您仍然不会 gt 地址、密码、电话号码的值,因为您尚未将其保存在 HashMap 中。为了获得更好的帮助,请发送您的 json 数据或为了解析 json 数据,只需从 json 中读取地址、密码、电话号码值并在将其添加到列表之前添加 hashmap。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-20
        相关资源
        最近更新 更多