I'm relatively new at developing applications in Android Studio or Java and recently ran into a problem I just can't figure out. For now, all I'm trying to achieve is to output the content of the EditText field after a Button is been clicked.
Since I will most likely add more buttons to the Activity later on, I thought that it would be more handy to use a generic onClick where you can separate different button actions inside the switch statement.
Here's a working example in which the onClickListener which does not use a generic onClick method:
package com.example.user.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize UI elements
final EditText testText = (EditText) findViewById(R.id.testText);
testButton = (Button) findViewById(R.id.testButton);
// set onClick listener
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// it will print the content of testText as long as the "testText" variable is declared as final
System.out.println(testText.getText().toString().trim());
}
});
}
}
Now, if I try to use a generic onClick method, I will suddenly receive a following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
Here's the code that that causes the error referred above:
package com.example.user.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the UI elements
EditText testText = (EditText) findViewById(R.id.testText);
Button testButton = (Button) findViewById(R.id.testButton);
// set onClick Listener
testButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.testButton:
// this will result in an error
System.out.println(testText.getText().toString().trim());
break;
default:
break;
}
}
Am I missing something here?
on your second code you have defined testText twice
that will work
package com.example.user.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the UI elements
testText = (EditText) findViewById(R.id.testText);
testButton = (Button) findViewById(R.id.testButton);
// set onClick Listener
testButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.testButton:
// this will result in an error
System.out.println(testText.getText().toString().trim());
break;
default:
break;
}
}
Decalre editText globally:
private EditText testText;
Get the view in onCreate():
testText = (EditText) findViewById(R.id.testText);
Use it in the onClick:
System.out.println(testText.getText().toString().trim());
You never initialize the private EditText testText; because you use a local variable instead of referencing the class field in the following call:
final EditText testText = (EditText) findViewById(R.id.testText);
The onClick(View v) is a method of anonymous class implementing the OnClickListener interface and this method references the uninitialized field variable testText.
To fix this, remove the type declaration of a variable before calling findViewById():
this.testText = (EditText) findViewById(R.id.testText)
You have declare EditText 2 time, one is globally and another one is inside the onCreate method, and when you are using Edittext outside the onCreate, you are getting global variable which is not initialize, thats why you are getting this error. use this,
public class MainActivity extends Activity implements View.OnClickListener {
private EditText testText;
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the UI elements
testText = (EditText) findViewById(R.id.testText);
testButton = (Button) findViewById(R.id.testButton);
// set onClick Listener
testButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.testButton:
// this will result in an error
System.out.println(testText.getText().toString().trim());
break;
default:
break;
}
}
Related
I caught the error message
"5-14 12:39:13.104 2518-2518/com.example.fdai3744.neueleereapp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.fdai3744.neueleereapp, PID: 2518 java.lang.RuntimeException: Unable to instantiate activity ..."
and here's my Java Code
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
#Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}
If I start my App the emulator throws an error message "App has stopped". How should I prevent this error?
Well, your view hierarchy needs to be alive before your retrieve individual Views from it and the method setContentView() brings it to life(or instantiates it).
How?
setContentView(View) is a method exclusively available for Activity.
Internally it calls the setContentView(View) of Window. This method
sets the activity content to an explicit view. This view is placed
directly into the activity's view hierarchy. Calling this function
"locks in" various characteristics of the window that can not, from
this point forward, be changed. Hence it is called only once.
So, instead of initializing the Views as instance variables, instantiate them inside onCreate() after setContentView().
Also read: Android: setContentView and LayoutInflater
caused by
public Button button_1 = (Button) findViewById(R.id.button1); //Button
public TextView text1 = (TextView)findViewById(R.id.text1); // Textview
never assign view before setContentView() is called
your modified code
package com.example.fdai3744.neueleereapp;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public Button button_1;
public TextView text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1 = (Button) findViewById(R.id.button1); //Button
text1 = (TextView)findViewById(R.id.text1); // Textview
button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button
#Override
public void onClick(View v) {
text1.setText("Button 1 wurde geklickt!");
}
});
}
}
im trying to understand variable scope with simple example.
I need help with this code
package com.varialescope.examplevariablescope;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button buttonOne;
private Button buttonTwo;
private String mText = "Hello World";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Initialialize UI elements
buttonOne = (Button) findViewById(R.id.button_one);
buttonOne = (Button) findViewById(R.id.button_two);
//Button One click listener
buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Set new text
mText = "ONE";
Toast.makeText(MainActivity.this, mText, Toast.LENGTH_SHORT).show();
}
});
//Button Two click listener
buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, mText, Toast.LENGTH_SHORT).show();
}
});
}
}
How can i access to mText string from click listener method ?
and how can i set a new string for mText clicking button One and make it accessible globally?
thanks for help
you create anonymous class Object for clicklistener any anonymous class or inner class object has information about the outside class object , then it had the right to access the methods and variables of the outside class object
I'm trying to implement onclicklistener but it isn't working on my phone or emulator.
here is the code:
package com.slaps.guess;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.tvd);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
tv.setText("Anything");
break;
}
}
}
the text view is not changing to anything it is still.
note: button1 exists, and their is nothing wrong with my xml.
i want to implement because i have alot of button.
You are missing one.setOnClickListener(this) in your code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
one.setOnClickListener(this);
tv = (TextView) findViewById(R.id.tvd);
}
Before using listener you will have to add it in the object for which you want it.
I guess you want for the Button one here.
Use one.setOnClickListener(this) after one = (Button) findViewById(R.id.button1);
It looks like you're missing the required XML attribute in res/layout/activity_main.xml. Ensure it looks like:
<Button
android:id="#+id/button1"
onClick="onClick"
/>
The key being you have supplied the onClick attribute with the name of your method to invoke.
But if you want to set the click listener programmatically than you will need to use the Button.setOnClickListener method. If you do this your method signature will need to change to:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
This code to change text when the user presses a button doesn't work. i tried to change it in some ways but i can't figure out why won't it change... please give me a bit help
package com.cookbook.simple_activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class activity extends Activity {
private TextView txt = (TextView) findViewById(R.id.hello_text);
Button startButton = (Button) findViewById(R.id.trigger);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
txt.setText(R.string.pressthisbutton);
}
});
}
}
Change it to
public class activity extends Activity {
private TextView txt;
Button startButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
txt = (TextView) findViewById(R.id.hello_text);
startButton = (Button) findViewById(R.id.trigger);
You need to initialize your Views after inflating your layout with setContentView(). Since your Views exist in your layout, they will return null if you haven't inflated your layout first. You can declare them before your setContentView() but you can't initialize them until after.
Also, since you are trying to access txt inside your listener it must either be final or declared as a member variable as above.
This was a rather easy one to spot but they aren't always. When you post a question try to describe what isn't working and how. Here it would be a NPE I'm guessing when you try to set the listener on your Button so it crashes. When it does crash, please provide the logcat so it is easier for us to spot the problem.
package com.cookbook.simple_activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
final TextView txt = (TextView) findViewById(R.id.hello_text);
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
txt.setText("your text");
}
});
}
}
try this, I moved your button and textview declaring to the body of the activity.
android life cycle always starts with onCreate() method assign the id inside the onCreate
don't use private modifer for the TextView
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class activity extends Activity {
TextView txt;
Button startButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
txt = (TextView) findViewById(R.id.hello_text);
startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
txt.setText(R.string.pressthisbutton);
}
});
}
}
Always initialize your textview and other widgets in oncreate method other wise youll get NullPointerException
Try this way
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
txt = (TextView) findViewById(R.id.hello_text);
startButton = (Button) findViewById(R.id.trigger);
txt.setText("It Working Now!!");
I have written this small app and it works perfectly. But I am new to java and assume there must be a better way to write this so that the variables can be read in both functions. Is there?
package max.multiplebuttons.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class multibuttons extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView question = (TextView)findViewById(R.id.question);
TextView textView = (TextView)findViewById(R.id.textView);
Button answer1 = (Button)findViewById(R.id.answer1);
Button answer2 = (Button)findViewById(R.id.answer2);
answer1.setText("button1");
answer2.setText("button2");
question.setText("click a button");
textView.setText("Some Text");
answer1.setOnClickListener(this);
answer2.setOnClickListener(this);
}
public void onClick(View v){
TextView textView = (TextView)findViewById(R.id.textView);
Button answer1 = (Button)findViewById(R.id.answer1);
Button answer2 = (Button)findViewById(R.id.answer2);
if(v==answer1){
textView.setText("1");
}
if(v==answer2){
textView.setText("2");
}
}
}
Make them variables that belong to the class by declaring them outside of any method but inside the class:
public class multibuttons extends Activity implements OnClickListener {
TextView question;
TextView textview;
//etc.
}
Then you just need to initialise them inside the onCreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
question = (TextView)findViewById(R.id.question);
textView = (TextView)findViewById(R.id.textView);
//...
You don't need to initialise them again at all in the onClick method:
public void onClick(View v){
if(v==answer1){
textView.setText("1");
}
if(v==answer2){
textView.setText("2");
}
}
Variables declared inside a method (or any block of statements enclosed by braces like {} ) only have scope (i.e. they are only visible) inside that method/block. Variables declared as class variables can be given public, private, protected or default/package scope. Declare them as public to be able to access them in any other class.