Below is what i have tried. "Forward" class extends Activity. It contains two buttons. In this class , we create two objects of "Collector" class using for loop. In the first iteration of the loop we create first button. In the second, we create one more button. we set "OnClickListener" for both the buttons. but only the second button responds for the click. First button doesnt respond to a click. I'm trying to use same variable name (b1) - I want to stick to OO Principle by not creating separate object for achieving my goal. - Also I'm expecting properties of 2 Objects as separate entity.Please help me. regards.
Forward.java (is an Activity, contains two buttons):
below is a for loop in which i create 2 objects of collector class.
for (int i = 0; i < 2; i++) { new Collector(this, i); } Collector.java :
public class Collector { Forwarder f; int n; Button b1; public Collector(Forwarder caller, int i) { f = caller; n = i; // 0 or 1 f.setContentView(R.layout.forwarder); switch(n) { case 0: b1 = (Button) f.findViewById(R.id.button1); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // get a new Contact Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); f.startActivityForResult(i, 1); // onActivityResult has to be implemented in f because // f extends Activity class } }); break; case 1: b1 = (Button) f.findViewById(R.id.button2); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // get a new Contact Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); f.startActivityForResult(i, 1); } }); break; default: } } }