Trần Hữu Nhật Huy Trần Hữu Nhật Huy - 3 years ago 84
Android Question

OnClickListener Error?

I'm building a program using some buttons. Everything is perfect and beautiful until this error popped up.

onclicklistener error

I tried as much ways as possible but it still doesn't work! Can you explain the error and the way to fix it? Thanks for your help! <3
Here is my code:

package com.huy9515gmail.mycontact;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
@BindView(R.id.edt_inputName) EditText edtName;
@BindView(R.id.btnAdd) Button btnAdd;
@BindView(R.id.edt_inputNumber) EditText edtNumber;
@BindView(R.id.rdbtn_male) RadioButton rdbtn_male;
@BindView(R.id.rdbtn_female) RadioButton rdbtn_female;
@BindView(R.id.rdbtn_others) RadioButton rdbtn_others;
@BindView(R.id.gender) RadioGroup genderSelection;
private ListView lvContact;


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

lvContact = (ListView) findViewById(R.id.lv_contact);
final ArrayList<Contact> arrContact = new ArrayList<>();

btnAdd.setOnClickListener(new View.OnClickListener() {
public void onclick(View v) {
//validating contact info
if (((edtName.getText().toString().trim()) == "") || (edtNumber.getText().toString().trim() == "")) {
Toast.makeText(MainActivity.this, "Invalid contact info! Please try again!", Toast.LENGTH_SHORT).show();
}
//adding contact info
else {
Contact contact = new Contact(Gender.male, "", "");

//receiving gender
boolean isMale, isFemale, isOthers;
if (rdbtn_male.isChecked()) contact.setGender(Gender.male);
if (rdbtn_female.isChecked()) contact.setGender(Gender.female);
if (rdbtn_others.isChecked()) contact.setGender(Gender.others);

//adding info
contact.setName(edtName.getText().toString());
contact.setNumber(edtNumber.getText().toString());

arrContact.add(contact);
}
}
});

CustomAdapter customAdapter = new CustomAdapter(this, R.layout.row_listview, arrContact);
lvContact.setAdapter(customAdapter);
}
}

Answer Source

Replace this line:

public void onclick(View v) {

With this (we just modified the capital C):

public void onClick(View v) {

It is a tricky thing, but since you're working with anonymous classes, you need to override the exact signature that the interface is giving you, and it's case-sensitive.

The implementation of the View.OnClickListener interface, requires you to implement the onClick method which receives one argument of type View.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download