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) {
}
});
}
}
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.
we got homework to make convertor of weights where the fields are updated while typing the number (no need to click "calculate" or anything). one of the students offered the code below.
the code works: when putting a number in field 1, field 2 changes while typing.
what i dont understand is how does that work?
in the onKey method, no value is given to View int and keyEvent
so how does the listener "knows" on which view to and what keys to listen to or what event to activate ?
public class Screen extends Activity {
double weight = 2.20462;
EditText kgEdit, lbsEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kgEdit = (EditText) findViewById(R.id.kgEdit);
lbsEdit = (EditText) findViewById(R.id.lbsEdit);
kgEdit.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
}
});
lbsEdit.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String lbs = lbsEdit.getText().toString();
if (lbs.isEmpty()) {
kgEdit.setText("");
} else {
double num = Double.valueOf(lbsEdit.getText().toString()) / weight;
kgEdit.setText(num + "");
}
return false;
}
});
}
}
I'm going to focus on just 1 of the text fields to answer this. Look at this first line:
kgEdit = (EditText) findViewById(R.id.kgEdit);
All this does is get a reference to the EditText for entering kg. Now that there is a reference, we can call methods on that object.
Next, we have this:
kgEdit.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// ...
}
}
What the above does is the following. Take our reference to the EditText for kilograms that we retrieved in our first line. The method setOnKeyListener does the following (from here): "Register a callback to be invoked when a hardware key is pressed in this view."
What this means is that you've now told the view that you want to be informed every time the user presses a key while this EditText has the focus. You make this call to the Android API and in the background Android handles everything you're asking. It will call the method with the View view, int keyCode and KeyEvent event. You give it a method that then handles those inputs. So nowhere in your code do you need to call the method, Android calls it in the background where you'll never have to see or worry about it.
Now, because you called the method on kgEdit, that means the following code will ONLY be called when kgEdit is focused and keys are typed, so there's no confusion with the other EditText. It gets its own method call later, just below. Here's the rest of the code inside the setOnKeyListener:
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
What this does is get the current text in kgEdit, which has already been updated with the key the user pressed. And it just checks if the text is empty, and if so remove the text in lbsEdit. If it's not empty, then get the text, convert it to a number, convert the number from kg to lbs and update lbsEdit
You have to use addTextChangedListener like this-
EditText editText = (EditText) findViewById(R.id.editText1);
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) {
//do here your calculation
String data = s.toString();
}
});
I am new to android development using JAVA, and I'm having an issue with a simple app I created. (Please don't laugh at it!)
All it's supposed to do is display a number in an editable textview; The three buttons on this main activity are a +, -, and reset. Super simple, right? I can't tell what I did wrong, but everytime I run the app to test, and then click on any of the buttons, it exits the app and goes back to the android home screen. Not sure what I did wrong... but here's the code I have so far:
public class Main extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn_Plus;
Button btn_Minus;
Button btn_Reset;
final EditText sCount= (EditText) findViewById(R.id.txtCount);;
btn_Plus=(Button)findViewById(R.id.btnPlus);
btn_Minus=(Button)findViewById(R.id.btnMinus);
btn_Reset=(Button)findViewById(R.id.btnReset);
//One way I tried to work it
btn_Plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//gets the text in the textview, makes it a string,
//converts it to an int, calculates, then puts it
//back.
String iCounter = sCount.getText().toString();
int iCount = Integer.parseInt(iCounter);
iCount += 1;
Integer.toString(iCount);
sCount.setText(iCount);
}
});
//The second way I tried -- neither way works.
bM.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int iCount = Integer.parseInt(sCount.getText().toString());
iCount -= 1;
if(iCount >0)
iCount = 0;
Integer.toString(iCount);
sCount.setText(iCount);
}
});
bR.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int iCount = 0;
Integer.toString(iCount);
sCount.setText(iCount);
}
});
}
}
Thanks so much!
Use a TextView instead, unless you plan to allow the user to directly enter the number (which it seems like you don't). Rather than do text manipulation to get the number, why don't you just store the number as a member variable, update that when a button is pressed, and change the text accordingly? This is how I would write it:
public class Main extends Activity {
int count = 0;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.txtCount);
findViewById(R.id.btnPlus).setOnClickListener(this);
findViewById(R.id.btnMinus).setOnClickListener(this);
findViewById(R.id.btnReset).setOnClickListener(this);
}
private void updateText() {
String text = Integer.toString(count);
textView.setText(text);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btnPlus:
count++;
break;
case R.id.btnMinus:
count--;
break;
case R.id.btnReset:
count = 0;
break;
}
updateText();
}
}
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
I'm trying to make an app that accepts an input and automatically changes it to an int. However, when it tries to obtain an int, the app automatically stops. Below is the full code...
public class MainActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculateTip);
calculate.setOnClickListener(this);
}//end onCreate
public void onClick(View v) {
EditText money = (EditText)findViewById(R.id.bill);
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}//end onClick
}//end MainActivity
I suspect that the application is stopping because the value you are trying to parse is not really an integer. You should throw that code into a try catch.
ie:
public void onClick(View v) {
EditText money;
try
{
money = (EditText)findViewById(R.id.bill);
// This check makes sure that the EditText is returning the correct object.
if(money != null)
{
int bill = Integer.parseInt(money.getText().toString());
money.setText("Event Processed");
}
}
catch(NumberFormatException e)
{
// If we get in here that means the inserted value was not an Integer. So do something.
//ie:
money.setText("Please enter a value amount" );
}
}//end onClick
Regardless, you should have this code in a try catch to maintain data integrity.
Hopefully this helps!
Cheers.
Are you sure that the Object is an instance of EditText and that it isn't null?