简体   繁体   中英

Android: Dynamicly add OnClickListeners to Buttons

In my Activity, I look into a SQLite database (_id, name, number) and add as many buttons as I have rows in the database. For each button I dynamicly create onClickListener that will start another activity into which I need to pass data from the coresponding database row. My code follows:

db.open();
String name;
String number;
Cursor c = db.getAllContacts();
c.moveToFirst();
int count = db.getCount();
for (int i = 0; i < count; i++) {
    ImageButton button = new ImageButton(this);
    name = c.getString(1);
    number = c.getString(2);
    button.setOnClickListener(new onClickListener() {
       public void onClick(View v) {
          Intent intent = new Intent(This_class.this, Other_class.class);
          intent.putExtra("name_bundle", name);
          intent.putExtra("number_bundle", number);
          startActivity(intent);
       }
    });
c.moveToNext();
}
db.close();

In the new Activity started by the ImageButton I work with the passed on data like this:

Bundle extras = getIntent().getExtras();
name = extras.getString("name_bundle");
number = extras.getString("number_bundle");

All the buttons are created correctly, but my problem is that all of them pass on the same information. My intention was that when third button is clicked, data (columns 1 and 2 in the code) from the third row in the database are passed (In the newly started Activity I display them in a TextView). But what happens is that all the buttons pass on the same data! Data from the last row of the database to be precise. When I tried to add yet another row to the database, one extra button was created and all of them again displayed the same data from the newly created (therefore the last) row of the database. I suspect either a dum mistake in my code or completly bad approach. Any ideas? Thanks!!

In your new Activity use removeExtra()

Bundle extras = getIntent().getExtras();
name = extras.getString("name_bundle");
number = extras.getString("number_bundle");
getIntent().removeExtra("name_bundle");
getIntent().removeExtra("number_bundle");

When you start activity old extras are not replaced by new.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM