I wanted to make an app that would get the test score from the text field (id etxt1) and on a click of a button it would show the grade in the other text field (id etxt2).
marks 100-91 grade A.
marks 90-81 grade B.
marks 80-71 grade C.
and so on.
and how to use the ">=" thing.
Here's my code:
Button bt1;
EditText etxt1;
EditText etxt2;
char grade = 0;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activitywhatsyourgrade);
bt1 = (Button) findViewById(R.id.button1);
etxt1 = (EditText) findViewById(R.id.testscore);
final int score = etxt1.getTextAlignment();
etxt2 = (EditText) findViewById(R.id.editText2);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (score == 90){
etxt2.setText("A1");
}
else if (score ==80){
etxt2.setText("A2");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activitywhatsyourgrade, menu);
return true;
}
There are a couple things wrong.
final int score = etxt1.getTextAlignment(); is incorrect because:
You define it outside of the button listener, and as final, so it never changes depending on input.
getTextAlignment() is not the function you want to call.
Here's how to fix it:
Get rid of that line of code all together. We'll replace that in the button listener.
We'll use getText() method to get the text from the EditText. It won't be returned as a String, but instead an Editable, so we'll use the toString() method on that to use it as a String.
Once we have the String representation of the score, we'll parse that to an integer to check which range of grade it's between.
This code is just for your button listener. Just replace it with this. It's self explanatory, so I won't give any more explanation for it.
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strScore = etxt1.getText().toString();
int score = Integer.parseInt(strScore);
if (score >= 91) {
etxt2.setText("A");
}
else if (score >= 81) {
etxt2.setText("B");
}
else if (score >= 81) {
etxt2.setText("B");
}
else if (score >= 71) {
etxt2.setText("C");
}
else if (score >= 61) {
etxt2.setText("D");
}
else {
etxt2.setText("F");
}
}
});
This next section is just extra, you don't have to read this part if you're not completely understanding the code so far:
You may run into a problem where if the field is left blank when the button is pressed, your app will crash. This is because you're trying to parse an empty string (which is "") to a numerical value, which obviously cannot be done. The same thing will happen if the field is just a negative sign or decimal point.
To fix that, you can just wrap the part of your code that is parsing the String to an integer in a try-catch block. This will catch an exception that will be thrown for the problem stated above. Like this:
Replace this line:
int score = Integer.parseInt(strScore);
With this:
int score = 0;
try {
score = Integer.parseInt(strScore);
} catch (NumberFormatException nfe) {
// This means NFE was thrown, so the field text cannot be parsed
// to a numerical value. Just leave score = 0 as it was initialized
}
Or you can use an if-statement to test if the input is valid (this solution is worse because it only catches three cases when there could possibly be more, depending on the keyboard restrictions):
int score = 0;
// if the input is not blank, a negative sign or a decimal point
if (!(strScore.equals("") || strScore.equals("-") || strScore.equals(".")) {
score = Integer.parseInt(strScore);
}
String a = etxt1.getText().toString();
etxt2.setText(a);
I would like to add an amendment to Mike Yaworski's answer
While this code is correct that he gave...
#Override
public void onClick(View v) {
String strScore = etxt1.getText().toString();
int score = Integer.parseInt(strScore);
...
... there is a fundamental flaw in that getText() can and will return null if the field is left blank. That is because it is not returning a String - it is returning an Editable; hence why you have to call toString() on it.
Here is my correction to it. Note, I had to get the text from 2 items in the GUI, so I separated the logic into a private method that returned the given String
// Returns a String from and Editable. Deals with the null value
private String extractStringNumber(Editable text) {
if (text == null) return "0"; // Change this to fit you needs
return text.toString();
}
#Override
public void onClick(View v) {
String strScore = extractStringNumber(etxt1.getText());
int score = Integer.parseInt(strScore); // This is now guaranteed not to fail as long as strScore can be represented as a number.
Related
I've got a [DONE] button that's supposed to check 2 entries's results. One of them is an [EditText--inputType:number] and the other is a [TextView] that increments when a certain button is pressed.
What I'm trying to do is check whether the EditText has an integer or is null, and check the contents of the TextView. if they both are greater than Zero. I add them up and send the total to my main activity. Here's the code i have so far.
public void returnbtn(View view) {
// Initialize insert textView
EditText insertcountBtn = findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
// get added int stuff from the insert textField
int insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
// convert counter textView to int.
Integer givencountInt = Integer.parseInt(givencountString);
if (givencountInt <= 0 && insertcountInt <= 0){
Total = 0;
} else if (givencountInt > 0 && insertcountInt <= 0) {
Total = givencountInt;
} else if (givencountInt <= 0 && insertcountInt > 0) {
Total = insertcountInt;
} else if (givencountInt > 0 && insertcountInt > 0){
// Add Counter textView and Insert textView to an Int Total
Total = givencountInt + insertcountInt;
}
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
// Pass the current number to the push-up Counter activity.
beginPushup.putExtra(TOTAL_DONE, Total);
// Start mainActivity.
startActivity(beginPushup);
}
The problem i'm having is with either textView or EditText i'm not sure. All i know is that if i fill them both and click done it adds them up and transfers the total to mainActivity as expected. If I add values to EditText and leave TextView with 0 it also does what it's meant to do. But if I increment TextView and leave EditText blank, it does not transfer my TextView integer and crashes app.
Could i be detecting the editText wrong, because i think that's the reason.
If so what's the right way?
----- First && Second Answer Edits -----
int insertcountInt;
String insertcountString =
String.valueOf(insertcountBtn.getText());
try {
insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
if (insertcountInt <= 0 || insertcountString == " ") Total =
givencountInt;
if (insertcountInt > 0 ) Total = givencountInt +
insertcountInt;
} catch (NumberFormatException e) {
insertcountInt = 0;
}
Good news is no more crash, but unless I fill the EditText with something, I'm not receiving my Integer in mainActivity. This is getting interesting. * I think it's a play of the if statements which I've restructures, but no luck so far. *
----- Updated Working Code For Any Future Requests -----
public void filledChecker() {
// Initialize insert textView
EditText insertcountBtn =
findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
int insertcountInt = 0;
int givencountInt = 0;
// get added int stuff from the insert textField
if (!TextUtils.isEmpty(insertcountBtn.getText()) &&
TextUtils.isDigitsOnly(insertcountBtn.getText())) {
insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
}
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
if (!TextUtils.isEmpty(givencountString) &&
TextUtils.isDigitsOnly(givencountString)) {
givencountInt = Integer.parseInt(givencountString);
}
if (insertcountInt <= 0) {
Total = givencountInt;
}
if (insertcountInt > 0) {
Total = givencountInt + insertcountInt;
}
}
public void returnbtn(View view) {
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
filledChecker();
Integer current_Id = getIntent().getIntExtra(GIVEN_ID, 0);
// Pass the current number to the push-up Counter activity.
if (current_Id == 1) beginPushup.putExtra(TOTAL_P_DONE,
Total);
if (current_Id == 2) beginPushup.putExtra(TOTAL_S_DONE,
Total);
if (current_Id == 3) beginPushup.putExtra(TOTAL_C_DONE,
Total);
if (current_Id == 4) beginPushup.putExtra(TOTAL_SQ_DONE,
Total);
beginPushup.putExtra(GIVEN_ID, current_Id);
// Start mainActivity.
startActivity(beginPushup);
}
I As you can see I ended up dividing the if-logic from the Intent to Transfer to main Activity. This way they're both simple. And using the Do Not Repeat Yourself i did the same thing to the rest of my other buttons as you can see with all the if's in [returnbtn] method. I also simplified the if statement aside from the ones i was helped with. I ended up needing 2 if statements to manage getting a total from the 2 entries. Thanks again for the help everyone. Ohh the try-except didn't seem necessary so i deprecated them. as the app gets more complex i'll add them if necessary.
As the other answer explained, the issue with your code is that when the EditText is blank then parsing "null" is causing exception. So you just have to insure that if content is null then just use 0(Zero) value. You can try this:
public void returnbtn(View view) {
// Initialize insert textView
EditText insertcountBtn = findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
int insertcountInt = 0;
int givencountInt = 0;
// get added int stuff from the insert textField
if (!TextUtils.isEmpty(insertcountBtn.getText()) && TextUtils.isDigitsOnly(insertcountBtn.getText())) {
insertcountInt = Integer.parseInt(insertcountBtn.getText().toString());
}
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
if (!TextUtils.isEmpty(givencountString) && TextUtils.isDigitsOnly(givencountString)) {
givencountInt = Integer.parseInt(givencountString);
}
if (givencountInt <= 0 && insertcountInt <= 0){
Total = 0;
} else if (givencountInt > 0 && insertcountInt <= 0) {
Total = givencountInt;
} else if (givencountInt <= 0 && insertcountInt > 0) {
Total = insertcountInt;
} else if (givencountInt > 0 && insertcountInt > 0){
// Add Counter textView and Insert textView to an Int Total
Total = givencountInt + insertcountInt;
}
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
// Pass the current number to the push-up Counter activity.
beginPushup.putExtra(TOTAL_DONE, Total);
// Start mainActivity.
startActivity(beginPushup);
}
TextUtils is a class provided in Android Framework.
This will check for if the content is not empty and also digits only. You can obviously omit the digit check if you are sure that only number will be the input of your edit text.
Because when your EditText is empty, it has no numerical value.
You can do
Integer.parseInt(insertcountBtn.getText().toString());
when the input is blank; there's no Integer value there, because there's nothing at all, so it's going to throw a NumberFormatException.
You can do the following to make sure it has a value (default will be 0 on failure):
int insertedcountInt;
try {
insertedCountInt = Integer.parseInt(insertcountBtn.getText().toString());
} catch (NumberFormatException e) {
insertedCountInt = 0;
}
The issue here is you are defining editText to check for only interger: you did not put the conditional statement for the cases like if String was entered, if editText is blank, it contains String. Hence, you may want to put something like;
String editTextString = String.valueOf(insertcountBtn.getText());
if (editTextString == "") {
//do something
}
Alternatively,
String editTextString = insertcountBtn.getText().toString();
if (editTextString == "") {
//do something
}
I'm trying to create a simple calculator that is automatic - no more equal sign. Here's how it should go:
1. User inputs the first number.
2. User chooses an operation "add", "subtract" etc.
3. User inputs the second number. In this stage, the program should now automatically compute the answer. For example:
user inputs "2" as the first number;
user chooses "add";
user inputs "3" (second number this time)
it should then display "5" in the result box.
if the user continues to input "2", this means the second number is now "32" instead of "3", and the result will be "34"
Here's my code:
public String int_firstnumber = "";
public String int_secondnumber = "";
public int int_result = 0;
public int int_numberone = 0;
public int int_numbertwo = 0;
public String str_operation = "";
public String str_inputdisplay = "";
public String str_indicator = "none";
public String str_focus = "first";
// BUTTON 1
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//checks the indicator
if(str_focus=="first") {
int_firstnumber = int_firstnumber +"1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
} else {
if(str_indicator=="add"){
int_secondnumber = int_secondnumber + "1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
int_numberone = Integer.parseInt(int_firstnumber);
int_numbertwo = Integer.parseInt(int_secondnumber);
int_result = int_numberone + int_numbertwo;
lblresult.setText(int_result);
}
}
}
});
//END OF BUTTON 1
//BUTTON ADD
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
str_indicator = "add";
str_operation = " + ";
str_focus = "second";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
}
});
This somewhat works but not completely. If I Input "1", it'll display 1 on the str_inputdisplay, I then click the + symbol or the btnadd, it then displays 1+ in the str_inputdisplay. This means that we are on the second number right? However when I input 1 again, the app just force closes.
Any ideas why this is happening? Forgive my ways of code, I just started learning Java btw. Thanks!
why are you naming your variable 'int_firstnumber' when it's a string public String int_firstnumber when all your other variables are named according to the variable type like int int_result and str_operation
your code looks a bit more complicated then it needs to be. as someone mentioned you can't add two numbers when your operator is a string i.e. string operator = "+"; it won't get treated like an operand, it will get treated for the type it is which is a string.
why not if they select "first" call a method setFirstNumber that way you can validate input and set the first number.. something like this:
public void setFirstNumber(int firstNumber){
int_numberone = firstNumber;
}
and then when "add" gets selected call a second method setSecondNumber along with an addition method
public void setSecondNumber(int secondNumber){
int_numbertwo = secondNumber;'
}
and
public int addNumbers(int firstNumber, int secondNumber){
return firstNumber + secondNumber;
}
your result will be int_result = addNumbers(int_numberOne, int_numberTwo)
this way your code is much cleaner, each function is executing one task, and if you want to add additional operations later it's easy to add a function subtract, multiply, etc
public int subtractNumbers(int firstNumber, int secondNumber){
return firstNumber - secondNumber;
}
public int multiplyNumbers(int firstNumber, int secondNumber){
return firstNumber * secondNumber;
}
hope that helps!
You should add TextWatcher to the input fields. You will get the values in callbaks there which you can use to update the view showing answer.
Two issues:
When adding two strings, addition will not happen. Change it to int, long etc when you want to do operation like:
int_firstnumber = int_firstnumber +"1";
Hopefully you are properly setting the variables str_focus and str_indicator because that is not available in the code snippet you have given.
if("first".equals(str_focus)) {
......
int_firstnumber = int_firstnumber +1;
} else {
if("add".equals(str_indicator)){
......
int_secondnumber = int_secondnumber + 1;
I'm trying to build a calculator that subtracts one textview from another. One of the textview has a constant value 5. The other textview gets its value after a user presses buttons from 0 to 9. There's also a button for a decimal sign (dot). So, for example, if I press buttons 4, 5, ., 6 and 7, the textview will show 45.67 and a third textview will present the answer (40.67).
This example works fine. But my problem is that I want to limit the number of integers (numbers before the dot) to three. Although I can do this by simply adding setMaximumIntegerDigits to 3, it doesn't work as I'd like. For example, if I press 4, 5 and 3, the textview shows 453. That's fine. However, if I then press another number, for example 7, it shows 537. If I press 8 after that, it shows 378, and so on.
The same problem doesn't exist for decimal numbers. So, my question is, how can I set the actual integer limit so that when I press a number for the fourth time, the application wouldn't change the number in textview?
The code:
public class MainActivity extends AppCompatActivity {
private TextView textResult;
private TextView textSubtractor;
private TextView textSubtractee;
private String display = "0";
private String result = "0";
private SharedPreferences mPrefs;
Button btnDone;
double num1, num2, sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult = (TextView) findViewById(R.id.textResult);
textSubtractor = (TextView) findViewById(R.id.textSubtractor);
textSubtractee = (TextView) findViewById(R.id.textSubtractee);
btnDone = (Button) findViewById(R.id.btnDone);
textSubtractor.setText(display);
textResult.setText(result);
mPrefs = getSharedPreferences("test", 0);
if (mPrefs != null){
display = mPrefs.getString("display", "0");
sub = mPrefs.getInt(result, 0);
}
updateScreen();
btnDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClickNumber(View v) {
if (v.getId() == R.id.btnDot && (display.equals("") || display.contains("."))) {
return;
}
if ((v.getId() == R.id.btn0 ||
v.getId() == R.id.btn1 || v.getId() == R.id.btn2 ||
v.getId() == R.id.btn3 || v.getId() == R.id.btn4 ||
v.getId() == R.id.btn5 || v.getId() == R.id.btn6 ||
v.getId() == R.id.btn7 || v.getId() == R.id.btn8 ||
v.getId() == R.id.btn9) && (display.equals("0"))) {
clear();
updateScreen();
}
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
df.setMaximumIntegerDigits(3);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
public void onClickClear(View v) {
clear();
}
private void clear() {
display = "";
result = "";
textSubtractor.setText("0");
textResult.setText("0");
}
private void updateScreen() {
textSubtractor.setText(display);
}
For a simple solution, I would suggest checking the integer and decimal part of the input when new numeric button is pressed:
//Class constants
final static int INTEGER_SIZE = 3;
final static int DECIMAL_SIZE = 2;
public void buttonPressed(View v) {
if (v.getId() == R.id.btn_dot){ // Handle dot
if(!display.contains("."))
display+=".";
}else{ // Only number values reach this
if(display.equals("0")){ // Handle default zero
clear();
updateScreen();
}
if(display.contains(".")){ //If the number contains a dot, decimal length has to be checked
String[] split = display.split("\\.");
if(split.length==2 && split[1].length()==DECIMAL_SIZE)
return; // New number is not added
}else if(display.length()==INTEGER_SIZE) //Otherwise check the length of the integer (whole sting)
return; // New number is not added
// New number will be added
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
}
In the long run, you should consider giving user some feedback like disabling the buttons or showing maximum length of the number on UI.
So here's my problem its been bugging me for a while but when I try to get the text from a textview (custom number picker) and add it as an array value, the array won't let me input the textview value (sonyR).
Custom number picker widget :
#Override
public void onClick(View v) {
String getString = String.valueOf(tvSony.getText());
int current1 = Integer.parseInt(getString);
if (v == btnUp1) {
if (current1 < nEnd) {
current1++;
tvSony.setText(String.valueOf(current1));
}
}
if (v == btnDown1) {
if (current1 > nStart) {
current1--;
tvSony.setText(String.valueOf(current1));
}
}
sonyR = current1;
Log.i("sonyR ouput =", String.valueOf(sonyR));
Array, if value has been entered before, find the value and display it. if not make a new array value
private void sun32() {
ArrayList<Integer> sun32A = new ArrayList<Integer>();
if (sun32A.contains(sonyR)) {
sun32A.get(Integer.valueOf(sonyR));
tvSony.setText(sonyR);
} else {
tvSony.getText(Integer.valueOf(sonyR));<-----here is the error
sun32A.add(sonyR);
}
return;
}
EDIT : Just to confirm here is an image of the UI layout
One problem in your posted code is that getText() shouldn't take any arguments.
Also, TextView.getText() returns a CharSequence, not a String. You should convert it by doing toString() before calling Integer.valueOf(). Try this code and see if it works:
ArrayList<Integer> sun32A = new ArrayList<Integer>(); <---- Variable moved to outside of method.
private void sun32() {
if (sun32A.contains(sonyR)) {
// removed irrelevant code line
tvSony.setText(String.valueOf(sonyR)); <----- Convert the int to String before setting text.
} else {
int myInt = Integer.valueOf(tvSony.getText().toString()); <----- fixed code
sun32A.add(myInt);
}
return;
}
I am trying to create an application that returns a score based on user input.
for example if the user has 1000 posts on a specific site it would return 1. i would end it at 10000.
1000 = 1
2000 = 2 etc.
here is what i have so far and thanks. this site is awesome.
for now i just have each entry adding. value1+value2 etc.
public class DataIn extends Activity {
EditText editPostCount;
EditText editThanksCount;
EditText editRomCount;
EditText editThemeCount;
EditText editKernelCount;
EditText editTutorialCount;
EditText editYearsJoined;
Button mButton;
TextView results;
Button mButton1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.data_in);
android.app.ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
editPostCount = (EditText)findViewById(R.id.editPostCount);
editThanksCount = (EditText)findViewById(R.id.editThanksCount);
editRomCount = (EditText)findViewById(R.id.editRomThreads);
results = (TextView)findViewById(R.id.results);
editThemeCount = (EditText)findViewById(R.id.editThemeCount);
editKernelCount = (EditText)findViewById(R.id.editKernelCount);
editTutorialCount = (EditText)findViewById(R.id.editTutorialCount);
editYearsJoined = (EditText)findViewById(R.id.editYearsJoined);
mButton = (Button)findViewById(R.id.results_button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calucate method.
calculate();
}
});
private void calculate() {
try {
Double value1 = Double.parseDouble(editPostCount.getText().toString());
Double value2 = Double.parseDouble(editThanksCount.getText().toString());
Double value3 = Double.parseDouble(editRomCount.getText().toString());
Double value4 = Double.parseDouble(editKernelCount.getText().toString());
Double value5 = Double.parseDouble(editThemeCount.getText().toString());
Double value6 = Double.parseDouble(editYearsJoined.getText().toString());
Double value7 = Double.parseDouble(editTutorialCount.getText().toString());
//do the calculation
Double calculatedValue = (value1+value2+value3+value4+value5+value6+value7);
//set the value to the textView, to display on screen.
results.setText(calculatedValue.toString());
} catch (NumberFormatException e) {
// EditText EtPotential does not contain a valid double
}
mButton1 = (Button)findViewById(R.id.clear_button);
mButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editPostCount.setText("");
editThanksCount.setText("");
editRomCount.setText("");
editThemeCount.setText("");
editKernelCount.setText("");
editTutorialCount.setText("");
editYearsJoined.setText("");
results.setText("");}
});
} }
You can get the score for every value using a simple division, that is cut to an integer.
In this example I also defined one constant to determine for each different value a specific score factor.
private static final int TOTALCOUNT_SCOREFACTOR = 1000;
int totalCountScore = totalCount / TOTALCOUNT_SCOREFACTOR;
I suggest you not to use doubles, generally int is enough.
I also suggest you to use an array of values, instead of defining all of them separately. In that way, you can easily add or remove values in future.
I hope I am not misunderstanding your question, but if you want the score to add 1 point for every 1000 posts, you simply get the number of posts and divide by 1000. for example:
//value1 is the post count
int calculatedvalue = value1/1000;
So if the number of posts(value1) is 3500, calculatedvalue would be 3.(the remainder is cut off during division)