I am creating dynamic layout in my code. My UI has multiple rows which are dynamically created at runtime. Each row consists of single edit text. I have created single edit text object and used this object to add in multiple rows.
Lets assume that there are 5 rows so there are 5 edit texts. User can enter/delete numbers in any of the edittext. Depending on what user enters in respective edittexts, I want to update the label.The label should contain addition of all edittext values.
I am calling following function on edit text afterTextChanged callback method.
private void refreshTotalNumberOfDays(Editable editable){
if(!(editable.length()==0)){
totalDays = Integer.parseInt(editable.toString());
}
finalTotalDays =totalDays+finalTotalDays;
ftotalNumberOfDays.setText(String.valueOf(finalTotalDays));
}
But its not adding values correctly.
You need to change to this:
totalDays = Integer.parseInt(editable.getText().toString());
It should give you the proper integer value.
To total all of them, keep an array of all the editTexts.
Make the array when you create the Activity
ArrayList<EditText> editTextArrayList = new ArrayList<EditText>();
editTextArrayList.add(editText1);
editTextArrayList.add(editText2);
...
Then on your callback Method, total them all up:
int total = 0;
for (EditText editText:editTextArrayList) {
total += Integer.parseInt(editText.getText().toString());
}
Related
I'm using this line to check on a number of views in my app and get the values associated with them, as input by the user. Every other view (odd) is a text view that's used as a title for the following view. These are created dynamically at runtime, and so I've collected the IDs into an arrayList to use in the following loop:
for(id in data.orEmpty()) {
val mView = findViewById<View>(id)
if (mView is TextView) {
Log.d("BEAU - ", "WOOT! ID number $id TextView - ${mView.text}")
}
if (mView is EditText) {
Log.d("BEAU - ", "WOOT! ID number $id EditText - ${mView.text}")
}
if (mView is RatingBar) {
Log.d("BEAU - ", "WOOT! ID number $id RatingBar - ${mView.numStars}")
}
}
The problem I'm having is that every EditText is being counted as both a TextView and an EditText; and so I'll have something like this:
D/BEAU -: WOOT! ID number 1 TextView - General EditText
D/BEAU -: WOOT! ID number 2 TextView - Hello World
D/BEAU -: WOOT! ID number 2 EditText - Hello World
However, all of the other things (like the rating bar) work perfectly. So, the question is, why is EditText passing a type check for text view; and is there something I can do to check for only text views and not text views and edit texts in the first if statement?
EDIT:
Temporarily, I've been able to check against EditTexts when checking for TextViews. I've done this like so:
if (mView is TextView && mView !is EditText) {}
But, is this right to do, and if so why should I have to do it like this?
Yiu need to put your chcecks in the right order. In this case as EditText extends TextView, you need to check first if this is EditText and then check its parent class (if you have longer inheritance chain, then you should check from the bottom of the hierarchy up to base/root class.
It's because EditText is a subclass of TextView, so this will give you true -
EditText is TextView
In EditText class you can see -
class EditText extends TextView { ... }
If it is suitable you can compare classes instead of checking types:
when (view.javaClass) {
TextView::class.java, AppCompatTextView::class.java -> {}
EditText::class.java, AppCompatEditText::class.java -> {}
RatingBar::class.java, AppCompatRatingBar::class.java -> {}
}
I'm new to android. I've an activity which consists of radio buttons, and on pressing each button it opens another activity which consists of EditText andTextView. The number of EditText and TextViews may vary according to each button press. I want to read data from all EditText and process it(like adding etc). The input to EditText is only integers.
For example on pressing a button an activity gets created with 5 EditText views. I want to add all the numbers that are entered to each EditText.
How can I do this?
You can get the input from edittext like
int a = Integer.parseInt(edittext.getText().toString());
Do this for all edittext you have in your currently activity. And then perform further action as needed in those integers.
You can set the output to textview like
textview.setText(someVar);
What you will have to do is get all the edittext value convert it to integer and add it.
Example would be:
lets say you have 3 edittexts.
private editText1,editText2,editText3;
private Button sum;
//on button click event do this
sum.setOnClickListener(view.OnClickListener(){
public void onClick(View v){
int a = Integer.parseInt(editText1.getText().toString());
int b = Integer.parseInt(editText1.getText().toString());
int c = Integer.parseInt(editText1.getText().toString());
//add these numbers
int totalSum = inta+intb+inc;
//Show the value in toast
Toast.makeText(getApplicationContext(),String.valueOf(totalSum),Toast.LENGTH_LONG),show();
}
});
The app crashes when the button is selected which uses the values converted from edit texts. Tried multiple ways to move the part edittext = R.ids .. to try and make sure the edittexts picks new values after the oncreate first runs.
Think the calculation part causes the crash because its trying to perform a calculation with stored values from the edit text when the value is false from the first time the edit text gets the R.ids... in the onCreate method.
needed hide/display editText based off a radio button setonCheckedChangeListener in the onCreate method. So edittext = R.ids .. set in this method, the app does not crash at runtime like it would if I moved the edittext = R.ids .. to the testFunction method.
EditText editTextValue;
EditText editTextValue2;
double amount;
protected void onCreate(){...
//Get edittext field parameters
editTextValue = (EditText) findViewById(R.id.editText_weight_kg);
//listener to switch editTexts on which radio button selected in units group
unitsRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.imperial) {
editTextValue2.setVisibility(View.VISIBLE);
editTextValue.setVisibility(View.GONE);
}
void testFunction(View view){
String stringValue = editTextValue..getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
}
but now when I run the app I get this error in the long cat
enter image description here
E/ClipboardServiceEx﹕ clipEx is android.sec.clipboard.ClipboardExManager#1f70b420
E/ClipboardServiceEx﹕ clipEx has text data : false
here is the xml for one of the edit texts
<EditText
android:id="#+id/editText_weight_lb"
style="#style/EditTextViewStyle"
android:visibility="visible"/>
In the editTextStyle , I set the textCursorDrawable to null to try and have different colors for the pointer and underline colors. Not sure if this could also be affecting the editTextView storing the value
<item name="android:textCursorDrawable">#null</item>
I also tried setting edittext = R.ids in the testfunction and in the onCreate method. See if the editTexts would store the values the user enters rather than keeping the empty values when onCreate initially run.
I still got the same clipEx has text data:false error after trying this.
I searched the logcat error "clipEx has text data: false" and found something regarding samsung memory leaks.
https://github.com/square/leakcanary/issues/133
I am using a samsung galaxy for testing. I feel the issue is more with where I'm setting the edittexts to the R.ids thats causing the issue.
I saw the post for checking to make sure valid value entered for edittext.
Issue with empty EditText
How to Check whether a value is entered in editexts before submitting?
will add the check after finding out why values are not getting stored/ still remaining false.
Thanks
well I tried a different approach to implement the method.
I placed a button in the OnCreate method to define the event handlers against the buttons:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
String stringValue = editTextValue.getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
.....
.....
}
}
By using the button method in the OnCreate, when I ran the app, errors would actually come up on the Integer.parseInt() method call. Turns out that even though the editTexts that I was entering text for did not have text values, the other editTexts still had strings for the text, so this would cause the app to crash.
<EditText...
android:text="kg"/>
I took out the text values. It worked again.
I also took out this line in the style sheet for the editText. This was to change the editText border color, cursor color, or line.
<item name="android:textCursorDrawable">#null</item>
I tried the public void testFunction() approach which I had used before, the app works, but the clipEx has text data : false continues to show up.
But the app works now with either the Button method in onCreate or as a public void testFunction() approach.
I've created a dialog containing two NumberPicker views. The first contains a list of groups, the second contains the items from the selected group:
Group Group Items
1 2: Group 2 Item 2
[2] [3: Group 2 Item 3]
3 4: Group 2 Item 4
I'm hooking in to the setOnValueChangedListener in the first NumberPicker to populate the second NumberPicker.
mNumberPickerGroup.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int from, int to) {
int size = mData.getItemsForGroup(to).size();
String[] strings = mData.getItemTitlesForGroup(to);
mNumberPickerItems.setMinValue(1);
mNumberPickerItems.setValue(1);
mNumberPickerItems.setMaxValue(size);
mNumberPickerItems.setDisplayedValues(strings);
}
});
This basically works - until, in certain circumstances, changing the group a few times can cause a crash in the NumberPicker class, when setting the setDisplayedValues strings.
The error is an array index out of bounds exception in the numberpicker for items, a line to do with the string array I passed in. I've set a break point in the update code above, and verified that the String array is always the correct size for the number of items set between min and max value on the number picker, so this has stumped me.
java.lang.ArrayIndexOutOfBoundsException: length=22; index=22
at android.widget.NumberPicker.ensureCachedScrollSelectorValue(NumberPicker.java:1768)
at android.widget.NumberPicker.initializeSelectorWheelIndices(NumberPicker.java:1583)
at android.widget.NumberPicker.setMaxValue(NumberPicker.java:1390)
at uk.co.my.app.fragments.GroupMarkUptoDialog.updateItemPicker(MarkUptoDialog.java:99)
I'm about to start reading through what happens in the NumberPicker to figure out if I'm using it wrong, but any suggestions would be welcome. "ensureCachedScrollSelectorValue" makes me think I need to reset the numberpicker somehow before updating it with new data but I'm not sure.
Can anyone see what I'm doing wrong here?
I realise the NumberPicker is not really a String picker, so if anyone has a better suggestion for how to achieve this sort of UI I'm all ears. Otherwise, I'm heading down the route of trying to implement some kind of debouncer, to update the items picker once all activity on the group picker is complete.
It happens when you setDisplayedValue(String[]) many times.
If the string[]'s length is larger than the current getMaxValue(), Exception happens!
My solution
use
picker.setMaxValue(0);
before
picker.setDisplayedValues(stringArr);
My code
cityPicker.setMaxValue(0);
try {
cityPicker.setDisplayedValues(citySet.toArray(new String[citySet.size()]));
} catch (Exception e) {
Log.e("Ninja", "cityPicker.setDisplayedValues(citys) occurs Error. province is " + province);
}
cityPicker.setMaxValue(citySet.size() - 1);
If you use indexes started from 1 then use:
int size = mData.getItemsForGroup(to-1).size();
Use this to change second picker (if current value is above maximum it will set it to new maximum):
int i = mNumberPickerItems.getValue();
int max = strings.length;
if (i > max)
i = max;
mNumberPickerItems.setMinValue(1);
mNumberPickerItems.setMaxValue(1);
mNumberPickerItems.setDisplayedValues(strings);
mNumberPickerItems.setMaxValue(max);
mNumberPickerItems.setValue(i);
And try to use values as indexes, i.e.
minValue=0
maxValue=strings.length-1
Ok im making app and it have 15 button's and 6 textview's.I want when I press first button to change value of first textview(value is "") to something (number one for example).But problem is when i press second button if first textview is already set to some value to set set second textview to second value.
If you need something else ask in comments (sorry for bad English)
here is what I was doing(this is under onclick)when i press second button
if(textview1.equals("1")){
textview2.setText("2");}
else if (textview1.equals("")){
textview1.setText("2");
}
It sounds like you wish to show last 6 buttons pressed.
Store all pressed buttons in a List (i.e. LinkedList) of size 6. Initially, it will be empty.
Then whenever any button is pressed do two things:
1) add it to the List and delete old elements if size exceeds six.
2) set button values from List.
Second step can be achieved like this:
// all TextViews should be in a list
private List<TextView> textViews;
// declare as field
private List<String> memoryQueue = new ArrayList<String>();
public void update() {
//set fields for the pressed buttons
for (int i=0; i<6 && i<memoryQueue.size(); i++) {
String text = memoryQueue.get(i);
textViews.get(i).setText(text);
}
// set empty fields
for (int i = memoryQueue.size(); i<6; i++) {
textViews.get(i).setText("");
}
}
This code snippet assumes that you store your TextViews in a List.
And Easiest way to keep track of last six button:
public void buttonPressed(Button button) {
//get text based on your button
String text = button.getText();
if (memoryQueue.contains(text)) {
return;
}
memoryQueue.add(text);
if (memoryQueue.size() > 6) {
memoryQueue.remove(0);
}
}
Since you're concerned with the text inside of your text view, you should be using the object's getText method:
if( textview1.getText().equals("1") ){ // Edited
textview2.setText("2");
} else if (textview1.getText().equals("")){ //Edited
textview1.setText("2");
}
At first, you have to get the String text from TextView using getText() method then you can compare that String with another String. Now, change your condition as follows...
if(textview1.getText().toString().equals("1")){
textview2.setText("2");}
else if (textview1.getText().toString().equals("")){
textview1.setText("2");
}