Extracting data from multiple EditTexts without code repetition - java

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());
}

Related

How do I output an integer to an EditText view?

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.

Empty editText causing app to crash when trying to calculate

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;
}

Java edittext to xml android

I am trying to do a app with multiple EditText and is wondering if there is any easy way to do that.
For instance to add matrix of EditText from your java code to your activity_main.xml or maby do a for loop which adds them at your specified location.
EditText[][] edittext = new EditText[10][10];
gridView = (GridView) findViewById(R.id.gridview);
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
gridView.addView(edittext[i][j], column X, row Y);
}
}
Here is a working example..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout root = (LinearLayout) findViewById(R.id.master);
EditText t[][] = new EditText[10][10];
LinearLayout.LayoutParams dim = new LinearLayout.LayoutParams(LinearLayout.LayoutParams
.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
t[i][j]=new EditText(this);
t[i][j].setLayoutParams(dim);
t[i][j].setHint("Hello World , EditText[" + i + "]" + "[" + j + "]");
root.addView(t[i][j]);
}
}
}
There is no easier way to make a "form". Each EditText is a different xml component with different id, with its own attributes.
What you can do is an adapter with listview/recyclerview with EditText the holder.
You can do smth like that:
ArrayList<EditText> editTexts = new ArrayList<>();
LinearLayout ll = (LinearLayout) findViewById(R.id.container);
EditText oneOfEditText;
for (int i = 0; i < 100; i++){
oneOfEditText = new EditText(this);
oneOfEditText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
oneOfEditText.setHint("MyHint");
oneOfEditText.setId(i);
ll.addView(oneOfEditText);
editTexts.add(oneOfEditText);
}
And then you can access these EditTexts like that:
for (EditText editText : editTexts){
Log.d("myLog", editText.getText().toString());
}
But the best practice for such things is to create them statically in xml, and then you can access them either via static ids, or like that:
for (int i =0; i < ll.getChildCount(); i++){
editTexts.add((EditText) ll.getChildAt(i));
}
I think the proper way implement each item is to use an adapter. In your case, you can use SimpleAdapter or create a custom adapter that extends BaseAdapter and set it using setAdapter(ListAdapter).
You can check the documentation for GridView here:
http://developer.android.com/guide/topics/ui/layout/gridview.html

Android Studio Button command

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
});

printing error for an empty input

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(""))

Categories

Resources