OnClickListener Error? - android

I'm building a program using some buttons. Everything is perfect and beautiful until this error popped up.
I tried as much ways as possible but it still doesn't work! Can you explain the error and the way to fix it? 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);
}
}

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.

Try to add #Override annotation if your Activity implements OnClickListener interface
And make the C capital like this:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your codes
}
}
});

You need to do exactly what the error is telling you to do.
You have to override the onClick method.
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);
}
}
});

Related

A simple app with a textview and two buttons that trigger toasts not working

It's just a simple text with two buttons that creates toasts and change the text. I'm very new to this AS so I really don't know how to even attempt to fix this..
Any help is very appreciated...
MainActivity.java:
package com.example.david.davidisawesome;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
final TextView firstText = (TextView) findViewById(R.id.firstText);
Button firstButton = (Button) findViewById(R.id.firstBtn);
Button secondButton = (Button) findViewById(R.id.secondBtn);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: First Button Clicked.");
toastMessage("You Clicked the first button");
firstText.setText("Nice Job.");
}
});
secondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Second Button Clicked.");
toastMessage("You Clicked the second button");
firstText.setText("Good Effort.");
}
});
}
private void toastMessage(String message){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
In picture:
activity_main.xml:
Error:
It is not finding your xml elements. The error shows that you have a null exception on setting the onclick interface to the button. So start by confirming that you are inflating the proper xml and finding the proper id.
More specifically your secondBtn is not found.

getText is not working in Android studio

package com.example.mediosa.mediosa;
import android.content.Intent;
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.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.firebase.client.Firebase;
public class registerActivity extends AppCompatActivity {
private Button buttonSignIn, buttonRegister;
private EditText editTextUsername;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextDOB;
private EditText editTextName;
private RadioButton radioButtonMale, radioButtonFemale;
private Firebase rootRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
rootRef = new Firebase(FIREBASE_URL");
buttonSignIn = (Button)findViewById(R.id.buttonSignIn);
editTextDOB = (EditText)findViewById(R.id.editTextDOBReg);
editTextUsername = (EditText)findViewById(R.id.editTextUsernameReg);
editTextEmail = (EditText)findViewById(R.id.editTextEmailReg);
editTextPassword = (EditText)findViewById(R.id.editTextPasswordReg);
editTextName = (EditText)findViewById(R.id.editTextNameReg);
radioButtonFemale =(RadioButton)findViewById(R.id.radioButtonFemale);
radioButtonMale = (RadioButton)findViewById(R.id.radioButtonMale);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(registerActivity.this ,
LoginActivity.class));
}
});
final String Name = editTextName.getText().toString();
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(registerActivity.this, Name ,
Toast.LENGTH_SHORT).show();
}
});
}
}
I am new to Android and was working on a project.
In this code (Part of that project) in am unable to read data from user as name. The compiler shows no error And the code works correctly but when i try to show the data in the Name string using toast, it is completely blank.
I need this name and other field to store data in Firebase DB, but it was not working and i found out there was some problem in reading data.
Would be really great if anyone can help me, thanks.
The problem is that you are not updating the value of Name , meanwhile there is no need for a variable if you only want to display the text. Here is how you display the text.
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(registerActivity.this,
editTextName.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
Try putting getText() inside the OnClickListener:
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name = editTextName.getText().toString();
Toast.makeText(registerActivity.this, Name ,
Toast.LENGTH_SHORT).show();
}
});
This is because you call getText() inside onCreate(). see where it is placed. Thus when the Activity is being created, the text inside EditText is empty.

Issue running a simple login app

I was learning to make a simple login app from youtube, however, when I build the code, although the app runs quite fine but it never assigns the value of 3 to the attempt counter later in the code, only the layout is visible and hence login doesn't work. Can you please help me? If you need any other file, write it in comment, I'll upload it later. Thanks.
package com.shubham.splashscreenemulation;
import android.content.Intent;
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.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
}
You don't call the function LoginButton() in your Activity.
Here some tips : function name starts with lowercase letter like loginButton ( with camelCase ), classes names starts with uppercase letter like AppCompatActivity. This tip is for more readability for the code. Why do you declare Views as static in that function?
package com.shubham.splashscreenemulation;
import android.content.Intent;
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.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
LoginButton();
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
You can add LoginButton() after setContentView or remove the LoginButton method, move everything inside onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--; attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
});
}
You can also change your setText to this attempts_left.setText(attempt_counter+"");

Nothing happens when I click on Button except when the EditText is empty

am new in android and facing a problem in edit text view need your help. I just want to check EditText before going on next intent. If EditText is filled by at least 1 String then it will go to next intent. May be this is simple for you to implement but this is to difficult for me and I wasted half day on this. Is anyone here which can tell me where is the mistake in this code.
Thank you in advance
package com.example.tricknearn;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Posttittle extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posttittle);
final EditText tittleInput = (EditText) findViewById(R.id.tittleInput);
Button postTittleButton = (Button) findViewById(R.id.postTittleButton);
postTittleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tittleInput.getText().length() == 0) {
tittleInput.setError("Please enter some text");
}
}
});
}
public void postTittleClick(View view) {
EditText tittleInput = (EditText) findViewById(R.id.tittleInput);
Intent i = new Intent(this, Postdescription.class);
if (tittleInput.getText().toString().equals("")){
}else{
startActivity(i);
}
}
}
Try this code instead...
public void postTittleClick(View view) {
EditText tittleInput = (EditText) findViewById(R.id.tittleInput);
Intent i = new Intent(this, Postdescription.class);
if (tittleInput.getText().toString().isEmpty()){
// Here you can place code while edit text is empty
}else{
startActivity(i);
}
}
postTittleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tittleInput.getText().toString().isEmptry()) {
//edittext is empty
tittleInput.setError("Please enter some text");
} else {
//Edittext is not empty
//start new Activity
}
}
});
And remove postTittleClick method
Replace if (tittleInput.getText().length() == 0) with if (tittleInput.getText().toString.equals(""))

ListView: Null pointer exception

Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.
The error specifically is
NullPointerException at line 76 at MainActivity
Here is the code of my MainActivity
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
final ArrayList<String> studentName = new ArrayList<String>();
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.listName);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);
myList.setAdapter(aa);
//droid.R.id.list;
//add
Button bAdd = (Button) findViewById(R.id.addstudent);
bAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
}
});
//edit
Button bEdit = (Button) findViewById(R.id.editstudent);
bEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
}
});
//edit
Button bDelete = (Button) findViewById(R.id.deletestudent);
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
}
});
}
public ArrayList<String> getArray(){
return studentName;
}
public void notifyArray(){
aa.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and line 76 by the way is
aa.notifyDataSetChanged();
Here is my code for the AddStudents class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddStudents extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_student);
Button bAddStudents = (Button) findViewById(R.id.add);
final EditText et = (EditText) findViewById(R.id.student_name);
bAddStudents.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
MainActivity as = new MainActivity();
as.getArray().add(et.getText().toString());
as.notifyArray();
finish();
}
});
Button bBack = (Button) findViewById(R.id.backadd);
bBack.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
and the xml part with the list view is
<ListView
android:id="#+id/listName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.
In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.
Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).
What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.
public class MainActivity extends Activity {
public static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
activity = this;
}
}
Then in your AddStudent class access it via
MainActivity.activity.notifyArray()
This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)
notifyArray() is being called before onCreate.
Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)
So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation
The common class may go something like:
class CommonHashtable{
private static Hashtable<String, Object> commonHashtable = null;
public static getInstance(){
if(commonHashtable == null)
commonHashtable = new Hashtable<String, Object>();
return commonHashtable;
}
on getInstance(), it returns a commonHashtable which can be used to store values temporarily!
so, add this on addbutton click event
Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());
and add this in you onResume() of MainActivity
Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");
if(studentName != null){
notifyArray();
}

Categories

Resources