Java Variable Scope Global - java

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

Related

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

setOnClickListener in simple Android does not work

I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.

How to access variables in separate functions - Android

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.

Categories