implementing onclicklistener is not working? - java

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
}
});

Related

Android Studio: App doesn't start with implemented Anonymous Java Class

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!");
}
});
}
}

Cannot output the contents of an EditText element inside onClick method

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;
}
}

OnClickListener and CheckBox Errors

I'm relatively new to app development and very confused about what to do here. Please be very clear and very detailed in your responses, much appreciated!
I'm getting a host of errors from the following code block:
//Blank out the appropriate blanks
chkRect.setOnClickListener(new onClickListener() {
#Override
public void onClick(View v) {
if (chkRect.isChecked()){
chkCyl.setEnabled(false);
txtDiameter.setText("0");
txtDiameter.setEnabled(false);
}
else {
chkRect.setEnabled(true);
txtDiameter.setText("");
txtDiameter.setEnabled(true);
}
}});
chkCyl.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v) {
if (chkCyl.isChecked()){
chkRect.setEnabled(false);
txtHeight.setText("0");
txtWidth.setText("0");
txtHeight.setEnabled(false);
txtWidth.setEnabled(false);
}
else {
chkRect.setEnabled(true);
txtHeight.setText("");
txtWidth.setText("");
txtHeight.setEnabled(true);
txtWidth.setEnabled(true);
}
}});
On both "onClickListener" lines and the 'public void' lines, the following shows up:
-onClickListener cannot be resolved as a type. (multiple lines)
-Method setOnClickListener(View.onClickListener) in the type View is not applicable for the arguments new onClickListener.
-The Method "onClick(View v)" must override or implement a supertype method.
Here are my imports and variable declarations:
import java.text.DecimalFormat;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
public class MaterialCalculator extends ActionBarActivity implements View.OnClickListener{
public Spinner materialDD;
public CheckBox chkRect;
public CheckBox chkCyl;
//public Spinner shapeDD;
DecimalFormat d = new DecimalFormat("#");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_calculator);
materialDD = (Spinner) findViewById(R.id.materialDD);
final CheckBox chkRect = (CheckBox) findViewById(R.id.chkRect);
final CheckBox chkCyl = (CheckBox) findViewById(R.id.chkCyl);
//shapeDD = (Spinner) findViewById(R.id.shapeDD);
Button btnCalculate = (Button) findViewById(R.id.btnCalculate);
Button btnClearAll = (Button) findViewById(R.id.btnClearAll);
final EditText txtDiameter = (EditText) findViewById(R.id.txtDiameter);
final EditText txtLength = (EditText) findViewById(R.id.txtLength);
final EditText txtWidth = (EditText) findViewById(R.id.txtWidth);
final EditText txtHeight = (EditText) findViewById(R.id.txtHeight);
final EditText edtTxtTotprice = (EditText) findViewById(R.id.edtTxtTotprice);
final EditText edtTxtWeight = (EditText) findViewById(R.id.edtTxtWeight);
I tried other solutions on this problem, including deleting the imports for view and onClickListener and using the ctrl+shift+O import, but it didn't work. Like I said, please be very specific with your answers since this is my first app and I'm not at all familiar with Eclipse to any great extent.
change
chkCyl.setOnClickListener(new onClickListener(){
with
chkCyl.setOnClickListener(new OnClickListener(){
and
chkRect.setOnClickListener(new onClickListener(){
with
chkRect.setOnClickListener(new OnClickListener(){
setOnClickListener takes as paramter an instance of a class that implements the OnClickListener interface
Maybe it can't get the variable from within the saved instance state? Try to define the variable right before the onClick Listener like this:
final CheckBox chkRect = (CheckBox) findViewById(R.id.chkRect);
chkRect.setOnClickListener(new onClickListener() {
#Override
public void onClick(View v) {
if (chkRect.isChecked()){
chkCyl.setEnabled(false);
txtDiameter.setText("0");
txtDiameter.setEnabled(false);
}
else {
chkRect.setEnabled(true);
txtDiameter.setText("");
txtDiameter.setEnabled(true);
}
}});
final CheckBox chkCyl = (CheckBox) findViewById(R.id.chkCyl);
chkCyl.setOnClickListener(new onClickListener(){
#Override`enter code here`
public void onClick(View v) {
if (chkCyl.isChecked()){
chkRect.setEnabled(false);
txtHeight.setText("0");
txtWidth.setText("0");
txtHeight.setEnabled(false);
txtWidth.setEnabled(false);
}
else {
chkRect.setEnabled(true);
txtHeight.setText("");
txtWidth.setText("");
txtHeight.setEnabled(true);
txtWidth.setEnabled(true);
}
}});

need some tips on my code, my code doesn't change text on Android

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!!");

Need an easier way to set up onClickListener for several variables in Android calculator program

I'm programming an Android calculator in Eclipse. I want to be able to set up the OnClickListener for several variables instead of having to code a listener for each one. Seems like overkill. Is there a way to do this using an array, maybe? Much help would be appreciated.
package rechee.cool;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
int counter=0;
//Just have two buttons so far, I'm going to have like 10 more
Button one;
Button two;
EditText display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Associate the button variable with the xml reference
one= (Button) findViewById(R.id.bOne);
display= (EditText) findViewById(R.id.editText1);
//When button is clicked, display the text. How do I do this for the rest of my variables?
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//String string= Integer.toString(counter);
display.setText("1");
}
});
}
}
The way I'd do this is add the same onClick attribute in XML to every button, like this:
<Button android:onClick="onButtonClick"
... />
and then add the method that you used in that attribute to your activity, differentiating the buttons by id:
public void onButtonClick(View v) {
switch(v.getId()) {
case R.id.button1:
// do something when button 1 is pressed
break;
case R.id.button2:
// do something when button 2 is pressed
break;
// and so on ....
}
}
Alternatively you can use findViewById() to get each button and assign the same listener to all the buttons. Then differentiate by id inside onClick()as shown above. This adds a few useless codelines though, so I think this example here is slightly more clean.
Yes you just need to override the onClick method of the Activity and tell it to implement the OnClickListener:
import com.ewe.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
int counter=0;
//Just have two buttons so far, I'm going to have like 10 more
Button one;
Button two;
EditText display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Associate the button variable with the xml reference
one= (Button) findViewById(R.id.bOne);
display= (EditText) findViewById(R.id.editText1);
//When button is clicked, display the text. How do I do this for the rest of my variables?
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//String string= Integer.toString(counter);
display.setText("1");
}
});
}
#Override
public void onClick(View v){
switch (case v.getId()){
case R.id.bOne:
//Put code for bOne here
break;
case R.id.editText1:
//Put code for editText1 here
break;
}
}
}

Categories