Passing dynamic string to activity

I create an activity with dynamic buttons in a loop. I get a list and create a button for each element in the list. The buttons go to the same activity afterward, but with each button I want to pass different string.

I did this in the loop:

    tour_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(TourListActivity.this,
                    TourMenuActivity.class);
            String info = tour.toString();
            intent.putExtra(TOUR_INFO, info);
            startActivity(intent);
        }
    }); 

But at the end, all the buttons get the same string (the string of the last button).

======================================== full code:

   try {
        JsonObject respObject = jsonParser.parse(response).getAsJsonObject();
        JsonArray tourListArray = respObject.getAsJsonArray("tours");
        System.out.println("tourListArray: " + tourListArray.toString());

        for(int i = 0; i < tourListArray.size(); i++){
            LinearLayout ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            tour = tourListArray.get(i).getAsJsonObject();
            String tourCode = tour.get("tourcode").getAsString();
            Button tour_button = new Button(this);  
            tour_button.setText("Tour Code: " + tourCode);
            tour_button.setGravity(Gravity.LEFT);
            tour_button.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(TourListActivity.this,
                            TourMenuActivity.class);
                    String info = tour.toString();
                    intent.putExtra(TOUR_INFO, info);
                    startActivity(intent);
                }
            }); 


            ll.addView(tour_button);

            LinearLayout yourLL = (LinearLayout) findViewById(R.id.Tours_List);
            yourLL.setOrientation(LinearLayout.VERTICAL);
            yourLL.addView(ll);  


        }
    } catch (JsonIOException e) {
        e.printStackTrace();
    } 

Answer

When you create the button you can:

 button.setTag(someString); 

and then in the onClick you can:

public void onClick(View v) {
        Intent intent = new Intent(TourListActivity.this,
                TourMenuActivity.class);
        String info = tour.toString();
        intent.putExtra(TOUR_INFO, ((Button)v).getTag());
        startActivity(intent);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *