When I execute the code, it always goes to the else condition. But I want the if statement to run when score=true; I cannot figure out how to do this...kindly help me out.
If not this way, is there any other way I can approach?
public class withComp extends Activity {
public boolean isPlayer2=false, score=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.withcomp);
final Button one = (Button)findViewById(R.id.one);
final TextView winner = (TextView)findViewById(R.id.winner);
one.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(isPlayer2==false)
{
one.setText("X");
score = true;
one.setEnabled(false);
isPlayer2 = true;
}
else
{
one.setText("O");
one.setEnabled(false);
isPlayer2=false;
}
}
});
if(score == true)
{
winner.setText("won");
}
else {
winner.setText("lose");
}
}
}
Just use
if(score)
Without the comma
You don't need to write
if (variable == true) or if (variable == false)
It's much better just to write
if (variable) or if (!variable)
You're executing the If-Else only once when the activity is created.
Move the if-else-code into the OnClickListener.
And of course remove the semicolon after the if.
For example:
public class withComp extends Activity {
public boolean isPlayer2=false, score=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.withcomp);
final Button one = (Button)findViewById(R.id.one);
final TextView winner = (TextView)findViewById(R.id.winner);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isPlayer2) {
one.setText("X");
score = true;
one.setEnabled(false);
isPlayer2 = true;
} else {
one.setText("O");
one.setEnabled(false);
isPlayer2=false;
}
// XXX Move it here
if (score) {
winner.setText("won");
} else {
winner.setText("lose");
}
}
});
}
}
Your problem lies in if(score == true);
if clauses do not need a semicolon after the condition, but a statement. Giving it a semicolon passes it the null statement, meaning nothing will happen.
After that it will execute both the blocks following, overwriting what happens in the block you intended to be executed if score is true.
You can fix this simply by removing the semicolon, letting it correctly execute the block.
Semicolon means end of statement.Remove ;
from if(score == true);
Use it this way"
if(score){
winner.setText("won");
}
else {
winner.setText("lose");
}
a few things,
one as already was pointed out, you are using semicolon ; after if statement, and i'm supprised you were able to compiled and execute this code
two, your if-else block is executed in method create and you setting value of score in listener, which means, blockif-else will be executed after you create your activity, while value score will be setted to true after press button
Related
This is the code that should let me go to next activity with 3 methods I made. The checkEditText method should take an editText parameter and change it to a string and then make sure it is not empty. The checkTextLetters should take the editText parameter and then make sure it contains only letters and/or spaces. Then the method configureNextButton should only run if the 2 previous methods are true:
private boolean checkEditText(EditText text){
if(text.getText().toString().trim().length() > 0)
{
return true;
}
//try and print to screen "name is left blank//
return false;
}
I would think this method would return true whenever I type asdf or something in the plain text:
private boolean checkTextLetters(EditText text){
String line = text.getText().toString();
//checks to make sure that the string contains only the characters a-z and A-Z and/or spaces
boolean checkChars = line.matches("[a-zA-Z]");
boolean checkSpaces = line.matches("\\s+");
if(checkChars && checkSpaces){
return true;
}
else if(checkChars){
return true;
}
return false;
}
This method should just take the text from the plain text that I typed in and check to make sure it only contains letters and spaces:
private void configureNextButton(boolean textCheck, boolean checkIfLetters){
//create if statement to not activate button if editText is empty
if(!textCheck || !checkIfLetters) {
return;
}
//will create variable 'mainButton' from the id of 'button' on MainActivity
Button mainButton = findViewById(R.id.button);
//sets the 'mainButton' to respond to a click
mainButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//states that when 'mainButton' is clicked, it begins Intent to switch to Main2Activity
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
This is the method where the button should take me to the next activity. I save 'checkEditText' method and 'checkTextLetters' to boolean variables and pass them on as the parameters for this method so that if they equal true then the code will let the button take it to the next activity and if either are false then it won't do anything:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editTextLines = findViewById(R.id.editText);
//call method to use 'button' to go to next activity given all conditions are true
boolean checkNotEmpty = checkEditText(editTextLines);
boolean checkIfLetters = checkTextLetters(editTextLines);
configureNextButton(checkNotEmpty,checkIfLetters);
}
Here is the main method where I put it all together and run it. It will work when I just set the checkNotEmpty and checkIfLetters to either true or false. Whenever I try and declare their value by calling my two methods then the button won't do anything.
I changed the code and got rid of the 'checkEditText' and 'CheckTextLetters' methods in place of a TextWatcher method in the main method. It works but has bugs. 1. When it first runs, I can press the button and it goes to the next activity. 2. I can enter any letter and nums but won't accept just nums. I want the EditText to simply, not work if it is empty, allow only letters and spaces
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editText = findViewById(R.id.editText);
final Button button = findViewById(R.id.button);
button.setClickable(false);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length() == 0)
button.setClickable(false);
else{
String line = s.toString();
boolean value = line.matches("[a-zA-Z]");
// set bool 'value' to check for alphabet letters
if(value)
button.setClickable(true);
}
}
});
//call method to use 'button' to go to next activity given all conditions are true
configureNextButton();
I think you need to use TextWatcher.
See this example code: Implement this with your logic and change existing function to accept String instead of EditText.
btnSubmit.setClickable(false);
edtText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length() == 0){
btnSubmit.setClickable(false);
}
else
{
//Validate if its Alphabets only - if returned true,
boolean value = validateAlphabetsOnly(s.toString());
if(value)
{
btnSubmit.setClickable(true);
}
}
}
});
In onCreate, activity is just created. User hasn't got any chance to write in EditText yet. So you will need to use TextChangedListener for EditText.
For many days now, I have been struggling to understand why the help that I found online didn't solve my issue, so I thought my best bet would be to ask here.
As a side note, I'm aware that my variable names aren't the best,and I am in general a newbie when it gets to Android development, but I think I can understand and I'm able sort issues fairly easily - except perhaps this thing.
I'm creating a simple app that allows me to get the total of profits of an item sold, so it would take the shipping price into consideration and do the calculation automatically. For this, when the shipping price would be left empty (blank), I would want to return a message saying it can't be empty, and a '0' must be entered to do the calculation. (My EditText field only allows numbers to be entered)
public class MainActivity extends AppCompatActivity {
double shippingNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shippingPrice = (EditText) findViewById(R.id.shippingPrice);
}
calculateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shippingNum = Integer.parseInt(shippingPrice.getText().toString());
if(shippingPrice.getText().toString().equals("") ||
shippingPrice.getText().length() == 0){
//shippingPrice.setText("0");
shippingPrice.setError("You can't leave this field empty! Enter something!");
}
I have also tried other variations such as:
if(TextUtils.isEmpty(shippingPrice.getText().toString().trim())){
shippingPrice.setError("You can't leave this field empty! Enter something!");
shippingPrice.setText("0");
}
But none of these seem to have allow me to leave the field empty without crashing. I've tried a dozen of different methods which I have realised that they were a waste of time as they wouldn't work - at least I've learned where I can use them.
Any help is much appreciated and thank you.
You could try just doing, check the length of the edit text, if zero display a toast saying enter more if not do the next part of the program:
if(getText().length() == 0){
Toast.makeText(getActivity(), "Enter values into field!",
Toast.LENGTH_LONG).show();
}
else{
// continue with the desired function of the program
}
Add this below method in your class :
public static boolean checkBlankValidation(EditText editText) {
if (TextUtils.isEmpty(editText.getText().toString().trim())) {
return false;
} else {
return true;
}
}
And call this method like below :
if (!checkBlankValidation(shippingPrice)) {
shippingPrice.requestFocus();
Toast.makeText(this, "Field should not be empty", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = findViewById(R.id.edittext);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() <= 0) {
editText.setError("This Field is required");
editText.requestFocus();
} else
editText.setError(null);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
How can i stop executing method when i click on a button??
I need a code that can stop executing codes in a specific method.
For example..
public class MainLoginActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
final Button lbutton = (Button) findViewById(R.id.buttonL);
lbutton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
///there i need a code that stop the execution of myMethod()
}
}
);
myMethod();
}
public void myMethod() { /*all codes i want*/ }
I would suggest the use of a boolean flag.
For example you would have a boolean flag called "stopExecution" which by default is set to false. This flag is then set to "true" by your button click event.
In your method you can then check before every statement whether this flag is still set to false. If so, execute the statement. If however the flag is set to true you would call "return" (or "break" depending on whether a loop is being use) to return from the method and stop executing any more code.
If you have a for loop the following could be done:
for(int i = 0; i < size; i++){
if(stopExecution){
break;
}else{
//execute statement
}
}
//Initializing clickCount
int clickCount = 0;
public void animateButton(View view) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickCount++;
if(clickCount%2==0 && clickCount==0){ //clickCount=0 declared in global variable
button.animate().translationX(400);
}
else {
button.animate().translationX(-400);
}
}
});
Or you can suggest any other method too.
Your if statement is true only once, at initialization. Afterwards clickCount is 1,2,3,... which is clickCount==0 : False so the if statement is also false.
I have Preference class extent PreferenceActivity.
I create public static String quality; in Preference.class i add in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
quality = "QUALITY_HIGH";//initialize
}
and add in Preference.class this method
public void getQuality() {
if (keyquality.equals("480p")) {
quality = "QUALITY_LOW";
//
}
if (keyquality.equals("720p")) {
//
quality = "QUALITY_720P";
}
if (keyquality.equals("1080p")) {
//
quality = "QUALITY_HIGH";
}
}
in another class i create method to get my variable and set settings
private void getqualityvideo() {
/*if (Prefernce.quality == null) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
} else {*/
if (Prefernce.quality.equals("QUALITY_LOW")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
}
if (Prefernce.quality.equals("QUALITY_720P")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
}
if (Prefernce.quality.equals("QUALITY_HIGH")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
}
// }
}
Problem:
when start application
private void startServes() {
btnStart = (ImageView) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.startAnimation(mAnimationImage);
Intent intent = new Intent(MainActivity.this, RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
changeCamera
.setEnabled(false);
btnStart.setEnabled(false);
setings.setEnabled(false);
moveTaskToBack(false);
}
});
}
in another class in method
getqualityvideo() error NullPointerException
error in this first line
if (Prefernce.quality.equals("QUALITY_LOW"))
why the quality variable is empty?
The reason is that you're setting Preference.quality in the onCreate method in your Preference class. So what's probably happening is that when you start your application in your other class, Preference.quality is going to be null because it was never initialized to anything. The reason is that the other class has no way to access the onCreate method in your Preference class as of now. onCreate is executed when an activity starts, but that doesn't seem to happen anywhere in your code. A solution could be to initialize public static String quality outside of your onCreate method but still within the Preference class,
public static String quality = "QUALITY_HIGH";
#Override
public void onCreate(Bundle savedInstanceState) {
//insert code here
}
The problem was merely a scope issue.