Getting a NullExceptionPointer on my setOnClickListener() - java

I'm getting a NullException error on my Button setOnClickListener() method. I'm a bit flabbergasted as to why this is happening. Please bear in my mind that this is my first Android app, and I assume that there are bound to be some runtime errors (there are no compilation errors).
btnNaira.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToNaira();
}
});
The dollarToNaira() method can be found here:
public void dollarToNaira() {
try {
dollarAmt = txtAmount.getText().toString();
nairaAmt = (Double.parseDouble(dollarAmt) * 199.00);
lblOutput.setText(dollarAmt + "U.S. Dollars = " + nairaAmt + " Nigerian Naira.");
}catch(Exception ex) {
message = "Please enter a valid numerical amount";
lblOutput.setText(message);
}finally {
txtAmount.requestFocus();
txtAmount.selectAll();
}
}
Please tell me what I am doing wrong I would like to know what causes the setOnClickListener method to return NULL. Thanks!
EDIT: this is the entire onCreate() method, I don't believe that I made an error:
protected void onCreate(Bundle savedInstanceState) {
txtAmount = (EditText) findViewById(R.id.txtAmount);
btnNaira = (Button) findViewById(R.id.btnNaira);
btnCFA = (Button) findViewById(R.id.btnCFA);
lblOutput = (TextView) findViewById(R.id.lblOutput);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//set up event listener on btnNaira and btnCFA
btnNaira.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToNaira();
}
});
btnCFA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToCFA();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}

there is no problem in your code.
i guess you've made a mistake in initializing buttons and text views.
1- make sure that you define your listener inside a method, like onCreate(),
i think you had defined that in class body.
2- i guess that you had defined your button or text views,
but you did not initialized them , so they are null.
here is an example of initializing a Button
Button btnDoSomething = (Button)findViewById(R.id.idOfButton);
now you can setOnClickListener for it .

You should write in this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtAmount = (EditText) findViewById(R.id.txtAmount);
btnNaira = (Button) findViewById(R.id.btnNaira);
btnCFA = (Button) findViewById(R.id.btnCFA);
lblOutput = (TextView) findViewById(R.id.lblOutput);
Make sure you call setContentView(R.layout.activity_main); before initialize your button View.
Hope it helps.

Related

setOnClickListener does not work in android studio

that is my code, very simple and basic
public Button btn1;
public TextView txt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.txt1);
findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});
and the error showing is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
The problem is here
findViewById(R.id.txt1);
findViewById(R.id.btn1);
you are getting the views from the .xml file but you are not actually assigning the value to any object... so when you try to call a method to the btn1 it's null (empty) and throws an error
So just assign the value you are getting to the views objects like so:
txt1 = findViewById(R.id.txt1);
btn1 = findViewById(R.id.btn1);
This will fix the problem
Save the element in variable and set onClick method to that particular variable as below:
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});

Floating Refresh-Button for WebView

I want to make a floating Refresh-Button for my WebView.
I did some research but I wasn't able to fix my problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String url = "https://www.rtl.de/cms/sendungen/serie/alarm-fuer-cobra-11.html";
WebView view = (WebView) this.findViewById(R.id.WebView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.reload();
}
});
I also tried MainActivity.this.webView.loadUrl("https://www.rtl.de/cms/sendungen/serie/alarm-fuer-cobra-11.html"); instead of view.reload(); but there is always an error.
Cannot resolve method 'reload()'
or
Cannot resolve symbol 'WebView'
It would be very nice if anyone could help me.
You can actually just make an Intent and start your current activity as a new one. For example in your activity, make a button like this:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
Please tell me if it is ok.
Take care!

Change Pictures by clicking Button [duplicate]

This code, with the block at the top commented, runs successfully:
public class MainActivity extends AppCompatActivity {
/*
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
*/
public void doLoginOnClick(View v)
{
String s1=username.getText().toString();
inputdata.setText(s1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
I am trying to capture id of component using
findViewById(R.id.***)
as you can see, I put this code in comment at the very beginning of the code.
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
If I remove the comment above and run it (both in emulator and real device), the program crashes immediately, I am surprised what's wrong here?
even I have tried to initialize the same thing using constructor.
But if I put it inside onCreate() there's no crash? Why?
I was trying to fetch info of username and password and display it to the textview in textView_Inputdata using
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
inputdata.setText(username.getText.toString()+" "+password.getText.toString());
Is there better or easier way to do that?
Instance member variables are initialized when the instance itself is initialized. It's too early for findViewById()
Before onCreate() your activity does not yet have a Window that findViewById() needs internally. Before setContentView() (that you should be calling in onCreate()) there are no views to be found either.
Therefore init your view references in onCreate() and after setContentView().
Add this code
EditText username = findViewById(R.id.editText_Username);
EditText password = findViewById(R.id.editText_Password);
TextView inputdata = findViewById(R.id.textView_InputData);
TextView welcome = findViewById(R.id.textView_Welcome);
Button login = findViewById(R.id.button_Login);
Button anotherLogin = findViewById(R.id.button_Login_Another);
in
onCreate();
method after
setContentView(R.layout.activity_main);
Hey I see that you are defining and initialising the instance variables.
What I do is I define the the instance variables - EditText username and then in the onCreate method I initialise them - username = (EditText) findViewById(R.id.editText_Username);
The reason you don't initialize the instance variables is because the elements are not ready until after the setContentView in onCreate method - I could be wrong with this, but my best practice is define the instance variable and then initialize them in the onCreate method
Before setting setContentView() you are not able to initialize the view items.Because view will not be exists for activity at that time.
Keep the initializations in one separate method and call that method after setting the view to the activity.
You must call findViewById() after setContentView() in onCreate(), before that there isn't UI/Layout initialize thats why your findViewById() unable to find ids and throws NullPointerException.
public class MainActivity extends AppCompatActivity {
public void doLoginOnClick(View v){
String s1 = username . getText ().toString();
inputdata.setText(s1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar =(Toolbar) findViewById (R.id.toolbar);
setSupportActionBar(toolbar);
EditText username =(EditText) findViewById (R.id.editText_Username);
EditText password =(EditText) findViewById (R.id.editText_Password);
TextView inputdata =(TextView) findViewById (R.id.textView_InputData);
TextView welcome =(TextView) findViewById (R.id.textView_Welcome);
Button login =(Button) findViewById (R.id.button_Login);
Button anotherLogin =(Button) findViewById (R.id.button_Login_Another);
FloatingActionButton fab =(FloatingActionButton) findViewById (R.id.fab);
fab.setOnClickListener(new View . OnClickListener ()
{
#Override
public void onClick(View view)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
Initialize all your views after onCreate() Method
Read More about activity lifecycle here
Think of it this way - until you tell the activity which user interface layout(xml) to use, it will not know where to get those views from.
You would do setContentView(R.layout.your_xml) to tell the activity which layout to use as the user interface for the activity. You would do this in the onCreate callback because this is the callback to do 'one-time activity level set up' tasks. setContentView() is one such task.
Once you do this, you can begin to access the views that are present within the layout file R.layout.your_xml.
onCreate(...)
{
...
setContentView(R.layout.your_xml)
// Ready to use the views from above xml.
findViewById(R.id.your_view)
...
}
View Binding will help you prevent from these issues:
https://developer.android.com/topic/libraries/view-binding
Or declare the views on top, and initialize them after setContentView() in onCreate().
public class MainActivity extends AppCompatActivity {
//Declare view on top
EditText username, password;
TextView inputdata,welcome;
Button login,notherLogin;
public void doLoginOnClick(View v)
{
String s1=username.getText().toString();
inputdata.setText(s1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set view
username = findViewById(R.id.editText_Username);
password = findViewById(R.id.editText_Password);
inputdata = findViewById(R.id.textView_InputData);
welcome = findViewById(R.id.textView_Welcome);
login = findViewById(R.id.button_Login);
anotherLogin = findViewById(R.id.button_Login_Another);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
} }
setContentView() is responsible for inflating the layout of the activity. If any of the components are used before inflation of the layout, it will crash with a NullPointerException.
#Override
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_layout);
username = findViewById(R.id.editText_Username);
password = findViewById(R.id.editText_Password);
inputdata = findViewById(R.id.textView_InputData);
welcome = findViewById(R.id.textView_Welcome);
login = findViewById(R.id.button_Login);
anotherLogin = findViewById(R.id.button_Login_Another);
}
You can still declare the variable in the beginning of the class, but you have to initialize it in onCreate.

if statement in Android Studio

I'm new to Android development, I am currently trying to see if a value entered is equal to a value. Here I am seeing if the user input equals to 5, they are currently set as strings as to is the text field.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uk_postage);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button home = (Button) findViewById (R.id.btnHome);
Button calculate = (Button) findViewById (R.id.btnCalculate);
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ukPostage.this, MainActivity.class));
}
});
EditText lengthInput = (EditText) findViewById(R.id.editTextLength);
final String lengths = lengthInput.getText().toString();
final TextView amount = (TextView) findViewById (R.id.txtAmount);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
if (lengths.equals("5")) {
amount.setVisibility(View.VISIBLE);
}
}
});
The text goes to visible if i click the button without the if statement there however won't once I write the if statement.
Thanks in advance.
if (lengths.equals("5")) {
String is immutable and once you reference it you need to reference it again with your edit text to reflect the latest value.
Instead of the above code you need to reference the lengths back with the lengthInput value each time you click the calculate button.
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
lengths = lengthInput.getText().toString();
if (lengths.equals("5")) {
amount.setVisibility(View.VISIBLE);
}
}
});
IMPORTANT: You need to set the lengths as a global variable instead of being a final variable since it can only be initialized once.

OnClickListener Android Studio

Hi I'm trying to create an application for Android, but when I try to start it with 2 setOnClickListener, it crashes,
Infact if i delete one of the two events it doesen't crash
how can I do?
P.S. Sorry for my bad english, but im italian
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that wil return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.FeedBackHome);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.contact);
}
});
Button button= (Button) findViewById(R.id.NotReg);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Register.class));
}
});
}
first illegal code :
you can't set new Content View onClick like you do here :
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.contact); // <-- this is wrong
}
});
be sure that Register.class contain layout and able to open from another activity.

Categories