Joshua
Joshua

Reputation: 29

Can't Instantiate the type

Have this code in my mainactivity.java file:

public class MainActivity extends Activity {

Button btnSendSMS;
/** Called when the activity is first created. */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
    btnSendSMS.setOnClickListener(new View.OnClickListener());
}

ADT says that : btnSendSMS.setOnClickListener(new View.OnClickListener()); cannot be instantiated.

Upvotes: 0

Views: 2671

Answers (4)

PermGenError
PermGenError

Reputation: 46408

ADT says that : btnSendSMS.setOnClickListener(new View.OnClickListener()); cannot be instantiated.

I believe View.OnClickListener() is either an abstract class or an interface. In java You cannot instantiate an interface or an Abstract class, thus you get an error. I believe you need an anonymous inner class in place of instantiation.

btnSendSMS.setOnClickListener(new ViewOnClickListener() {
       //your implemneting method from ViewOnClickListener     
});

Upvotes: 0

mspringsits
mspringsits

Reputation: 53

btnSendSMS.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });
    }

1)That's the implementation you need! 2)Try to rebuild your project anyway!

Upvotes: 0

Grzegorz Żur
Grzegorz Żur

Reputation: 49171

If you want to add anonymous click listener do it that way

btnSendSMS.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick (View v) {
          // your code
     }
});

Upvotes: 0

Mena
Mena

Reputation: 48404

You cannot intantiate a View.OnClickListener with an empty constructor. You need to instantiate an anonymous class for that.

Example:

btnSendSMS.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    // TODO your code
    };
});

Upvotes: 1

Related Questions