I have an EditText as input. I am trying to use it for output as well. I've tried the following:
FoodIncomeCounter.setText(TotalFood.getText().toString());
FoodIncomeCounter = Integer.parseInt(TotalFood.getText());
String FoodIncomeCounter = String.valueOf(TotalFood);
and nothing works. For the 1st and 2nd option the "getText()" cannot be resolved. Am I able to output to an EditText view, or do I need to make a separate TextView and output to that? Hopefully that all makes sense to you. My goal is to be able to use the FoodCampX and FoodUpgradeX variables to calculate the income and output that into FoodIncomeCounter variable/EditText view (which currently you can manually input). FoodIncomeCounter is an EditText view, FoodCampX and FoodUpgradeX and FoodIncome are integers, TotalFood is an integer. Thank you for teaching me.
Here is the code:
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
}
//Buttons
public void onClick(View v) {
switch (v.getId()) {
case R.id.IncomeSubmitButton:
//reset to value
FoodIncomeCounter.setText("");
//receive the inputted values
FoodIncome = Integer.parseInt(FoodIncomeCounter.getText().toString());
break;
case R.id.FoodCampSubmitButton:
//reset to value
FoodCamp1Counter.setText("");
FoodCamp2Counter.setText("");
FoodCamp3Counter.setText("");
FoodUpgrade1Counter.setText("");
FoodUpgrade2Counter.setText("");
FoodUpgrade3Counter.setText("");
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
//These 3 options are what iv tried and do not work
FoodIncomeCounter.setText(TotalFood.getText().toString());
FoodIncomeCounter = Integer.parseInt(TotalFood.getText());
String FoodIncomeCounter = String.valueOf(TotalFood);
//------------------------------------------------------
break;
default:
break;
}
}
Change
FoodIncomeCounter.setText(TotalFood.getText().toString());
to
FoodIncomeCounter.setText(String.valueOf(TotalFood));
As getText() is a method on components like EditText, TextView, and not datatypes.
Based on some educated guesses on the types of your fields, the following should work, as TotalFood is probably a number:
FoodIncomeCounter.setText(String.valueOf(TotalFood));
getText() is a method on EditTexts but it doesn't work on numbers.
Related
I'd like to efficiently extract data from the EditText fields in a form, without having to repeat the same code multiple times. Here's my current implementation for four EditTexts:
EditText editText1 = (EditText) findViewById(R.id.editText1);
String message1 = editText1.getText().toString();
formData.put("data1", message1);
EditText editText2 = (EditText) findViewById(R.id.editText2);
String message2 = editText2.getText().toString();
formData.put("data2", message2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
String message3 = editText3.getText().toString();
formData.put("data3", message3);
EditText editText4 = (EditText) findViewById(R.id.editText4);
String message4 = editText4.getText().toString();
formData.put("data4", message4);
The general ways for not repeating code are usually loops and functions. In this case you should add your EditTexts to an array like data structure and loop over them.
For example:
You could store the edit Texts in a Hash map and then use a loop to add them to the form:
new HashMap<EditText, String>() {{
put(R.id.et1, "name");
put(R.id.et2, "phone");
//etc...
}}.forEach((editText, s) -> formData.put(s, editText.getText().toString()));
If you don't mind using uninformative names you can just use an array:
EditText[] toAdd = new EditText[]{findViewById(R.id.et1), findViewById(R.id.et2)};
for (int i = 0; i < toAdd.length; i++) {
formData.put("data" + i, toAdd[i].getText().toString());
}
Or for a nice mix of both, you can use the ID of the EditText as the name
EditText[] toAdd = new EditText[]{findViewById(R.id.et1), findViewById(R.id.et2)};
for (EditText editText : toAdd) {
formData.put(getResources().getResourceEntryName(editText.getId()), editText.getText().toString());
}
I have an app with 4 EditText and one button that is supposed to calculate the inputs given
When one of those are left empty then the app crashes
How can I validate to throw an error when a EditText is left empty
You can use TextUtils.isEmpty(stringData) and it is preferred. For string.isEmpty(), a null string value will throw a NullPointerException.
TextUtils will always return a boolean value. In code, the former simply calls the equivalent of the other, plus a null check.
EditText myEditText1 = findViewById(R.id.editText1);
EditText myEditText2 = findViewById(R.id.editText2);
EditText myEditText3 = findViewById(R.id.editText3);
EditText myEditText4 = findViewById(R.id.editText4);
String myData1 = myEditText1.getText().toString();
String myData2 = myEditText2.getText().toString();
String myData3 = myEditText3.getText().toString();
String myData4 = myEditText4.getText().toString();
if(!TextUtils.isEmpty(myData1) && !TextUtils.isEmpty(myData2) && !TextUtils.isEmpty(myData3) && !TextUtils.isEmpty(myData4)) {
//use edit text data
} else {
Toast.makeText(this, "Fields value can not be empty",Toast.LENGTH_SHORT).show();
}
When you click the button check if the EditText is empty or not
Try below code
if(editText.getText().toString.length() == 0){
// Display toast
Toast.makeText(getApplicationContext(), "Please enter something !",Toast.LENGTH_LONG).show();
}
Or you can use a library called AwesomeValiation
First you need to link the edit text and button with the id
EditText editText1 = findViewById(R.id.editText1);
EditText editText2 = findViewById(R.id.editText2);
EditText editText3 = findViewById(R.id.editText3);
EditText editText4 = findViewById(R.id.editText4);
Now you can get the value from the editText by using the below code
String data = editText.getText();
For check the null value
if (data.isEmpty ){
Toast.makeText(getApplicationContext(),"the data is "+data,Toast.SHORT_LENGTH).show;
}
I've created a string which is a random string from an array. The user presses a button and the function executes again, showing the user a new string from the array.
This is what I have thus far, which doesn't quite work:
String[] letters = {"s", "a"};
String randomSad = (letters[new Random().nextInt(letters.length)]);
tv1 = (TextView) findViewById(R.id.textview11);
tv1.setText(randomSad);
Always provide the code that you have already tried. But this being a simple implementation, it should look like this :
String[] nameList = {"Sam", "Harry", "Ron"}; //Store the list as you like
int index i = 0;
//put the correct id of the TextView from the xml file
TextView nameTextView = (TextView) findViewById(R.id.nameTextView);
//put the correct id of the Button from the xml file
Button button = (Button) findViewById(R.id.button1);
//set the OnclickListener and define what you want to happen in the onClick() method
button.setOnClickListener(new OnclickListener() {
nameTextView.setText(nameList[index]); //set the name in the index as text
if((index+1) >= nameList.length)
index++; //increase the index by 1, for the next time.
else
index = 0; // to loop back to the first name.
});
If you want the last name to stay even if the butten is pressed again, cut out the else part.
Edit :
()After you provided the code
String[] letters = {"s", "a"};
String randomSad = (letters[new Random().nextInt(letters.length)]);
tv1 = (TextView) findViewById(R.id.textview11);
tv1.setText(randomSad);
button.setOnClickListener(new OnclickListener() {
randomSad = (letters[new Random().nextInt(letters.length)]);
tv1.setText(randomSad); //set the name in the index as text
});
I am trying to do a calculator app for android where i take two inputs for 2 numbers and output the result along with the function it does(i.e. addition or subtraction...).
public void Add(View view)
{
float a=0,b=0,res=0;
EditText num1 = (EditText) findViewById(R.id.editText1);
EditText num2 = (EditText) findViewById(R.id.editText2);
TextView function = (TextView) findViewById(R.id.textView4);
TextView ans = (TextView) findViewById(R.id.textView5);
a=Float.parseFloat(num1.getText().toString());
b=Float.parseFloat(num2.getText().toString());
String str1 = Float.toString(a);
String str2 = Float.toString(b);
if(str1=="")
{
function.setText("Enter both Numbers");
ans.setText("");
return;
}
if(str2=="")
{
function.setText("Enter both Numbers");
ans.setText("");
return;
}
res=a+b;
String str = Float.toString(res);
function.setText("addition");
ans.setText(str);
}
so this is what i am doing. i take 2 inputs. convert them to float variables a and b. now my issue is if the user did not input an input and try for the solution, then i must produce some error saying 'enter both the numbers'. on doing it as above it's not working.
nor does it works in this manner
if(str1=='\0')
{
function.setText("Enter both Numbers");
ans.setText("");
return;
}
this produces error when the input is zero.
So please help how to identify if there is no input given and to produce the error at that time.
Put the test before converting to Float.
Your test need to be some thing like this:
if (num1.getText().toString().trim().isEmpty()){
// show error
}
Use:
if(str1==null || str1.trim().equals(""))
Is there any way to predefine a value for strings in order not to have the error when any of the fields are empty?
All porcentagem 1, 2 and 3 are optional, so it's not the case to ask the user to input some data, but predefine values in order not to have the values. Beginner question.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cpc_inicial = (EditText) findViewById(R.id.cpc_inicial);
porcentagem1 = (EditText) findViewById(R.id.porcentagem1);
porcentagem2 = (EditText) findViewById(R.id.porcentagem2);
porcentagem3 = (EditText) findViewById(R.id.porcentagem3);
cpc_final = (TextView) findViewById(R.id.cpc_final);
botao1 = (Button) findViewById(R.id.botao1);
cpc_inicial.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem1.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem2.setInputType(InputType.TYPE_CLASS_NUMBER);
porcentagem3.setInputType(InputType.TYPE_CLASS_NUMBER);
botao1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(porcentagem3 != null ) {
float cpc = Float.parseFloat(cpc_inicial.getText().toString());
float v1 = Float.parseFloat(porcentagem1.getText().toString());
float v2 = Float.parseFloat(porcentagem2.getText().toString());
float v3 = Float.parseFloat(porcentagem3.getText().toString());
TextView cpcfinal = cpc_final;
if(cpc > 0.0 && v1 != 0.0 && v2 != 0.0 && v3 != 0.0 )
{
soma = (cpc*v1/100)+cpc;
soma = soma*(v2/100)+soma;
soma = soma*(v3/100)+soma;
String sum = Float.toString(soma);
cpcfinal.setText(sum);
}
} else
{
TextView cpcfinal = cpc_final;
soma = 0;
cpcfinal.setText("ops!"); }
}
});
}
Thanks
Every time a form is submitted, you should check whether each field has a proper value. For example, if you want to check weather an optional field has a value or not, you should do something like this:
String optionalText = optionalFieldName.getText().toString();
if (optionalText.equals("some expected value")) {
//Do something with the value here.
}
Of course, you would need to do something similar for every optional field, and really should also do the inverse for fields that are not option to be safe, and perhaps warn the user that the field is required, for example:
String text = fieldName.getText().toString();
if (text.equals("")) {
//field is empty, so warn the user that it is required.
}
If the value you are looking for should be numerical in nature, then you should do something like this:
String text = field.getText().toString();
if (!text.equals("")) {
//Field has at least some text in it.
try {
float val = Float.parseFloat(text);
}catch (NumberFormatException ex) {
//Enterered text was not a float value, so you should do something
// here to let the user know that their input was invalid and what you expect
}
//Do something with the value
}
Either add the values to your xml layout using the android:text="..." attribute or use TextUtils.isEmpty(...) to detect if the string is empty and assign a default value yourself.