I'm trying to use a togglebutton to display the status of a number check when the number is entered in a textbox. I've already set it up with a TextView and that works fine but I'd like to replace it graphically. No errors are thrown up with the following but the state doesn't change with the .SetChanged events in the OnChanged event:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ToggleButton togShortCircuit = (ToggleButton) findViewById(R.id.togShortCircuit);
togShortCircuit.setClickable(false);
final EditText txtOCVListen = (EditText) findViewById(R.id.txtOCV);
txtOCVListen.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
txtOCVListen.setFilters(new InputFilter[]{new CustomRangeInputFilter(0f, 16.0f)});
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(txtOCVListen.getText().toString().equals(null) || txtOCVListen.getText().toString().equals("")){
fltOCV = 0;
} else {
fltOCV = Float.parseFloat(txtOCVListen.getText().toString());
}
//Short Circuit
if (fltOCV < 10.6 && fltULV > 0 && fltULV <= 8.5) {
TextView lblShortCircuitStatus = (TextView) findViewById(R.id.lblShortCircuitStatus);
lblShortCircuitStatus.setText("True");
lblShortCircuitStatus.setTextColor(0xFFD51817); //Red
togShortCircuit.setChecked(true);
} else {
TextView lblShortCircuitStatus = (TextView) findViewById(R.id.lblShortCircuitStatus);
lblShortCircuitStatus.setText("False");
lblShortCircuitStatus.setTextColor(0xFF808080); //Grey
togShortCircuit.setChecked(false);
}
Can't seem to figure out how to declare togShortCircuit to have it recognized with the event. Using Android Studio 3.12 and developing for Android 7.0.
Related
I'm using Android Studio to develop a program which adds two numbers. First, I used a button to start the calculation but now I don't want to use that button anymore so I'm searching for a possibility to add two numbers in real time. If I change one number, the result should appear instantly. Do you have any suggestions?
This is my code für the button variant:
New code:
public class MainActivity extends AppCompatActivity {
EditText firstNumEditText, secondNumEditText;
TextView resultTextView;
class MyTextWatcher implements 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) {
String second = secondNumEditText.getText().toString().trim();
String first = firstNumEditText.getText().toString().trim();
int num1 = Integer.parseInt(second);
int num2 = Integer.parseInt(first);
int result = num1 + num2;
resultTextView.setText(result + "");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
firstNumEditText.addTextChangedListener(new MyTextWatcher());
secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
secondNumEditText.addTextChangedListener(new MyTextWatcher());
resultTextView = (TextView) findViewById(R.id.resultTextView);
}
}
LogCat's output:
java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:533)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.aufgabe2.MainActivity$MyTextWatcher.afterTextChanged(MainActivity.java:33)
at android.widget.TextView.sendAfterTextChanged(TextView.java:8202)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:10381)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1218)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:579)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:509)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:508)
at android.text.method.NumberKeyListener.onKeyDown(NumberKeyListener.java:121)
at android.widget.TextView.doKeyDown(TextView.java:6284)
at android.widget.TextView.onKeyDown(TextView.java:6074)
at android.view.KeyEvent.dispatch(KeyEvent.java:2676)
at android.view.View.dispatchKeyEvent(View.java:9880)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1667)
at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:403)
at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1800)
at androidx.core.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:130)
at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:126)
at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:535)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2533)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:317)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4327)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4298)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3995)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4052)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6210)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6184)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6145)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3647)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
TextWatcher can help you dynamically get value from EditTexts:
I added an inner class to implement TextWatcher
Passed an Object from that inner class to editText.addOnTextChangedListener
I used afterTextChanged() to get result from both EditText and perform my operation.
public class MainActivity extends AppCompatActivity {
private EditText firstNumEditText, secondNumEditText;
private TextView resultTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstNumEditText= findViewById(R.id.firstNumEditText);
firstNumEditText.addTextChangedListener(new MyTextWatcher());
secondNumEditText=(EditText) findViewById(R.id.secondNumEditText);
secondNumEditText.addTextChangedListener(new MyTextWatcher());
resultTextView=(TextView) findViewById(R.id.resultTextView);
...
}
class MyTextWatcher implements 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) {
String second = secondNumEditText.getText().toString().trim();
String first = firstNumEditText.getText().toString().trim();
if (!second.isEmpty() && !first.isEmpty()) {
try {
int firstNumber = Integer.parseInt(first);
int secondNumber = Integer.parseInt(second);
//Do calculation
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
You could use TextWatcher on your EditText to listen the text change event and perform action like Add or Minus.
You can do it by adding addTextChangedListener to the editText.
editText.addTextChangeListener(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) {
// here you can extract the value from edit text and do the addition
}
#Override
public void afterTextChanged(Editable s) {
}
});
I am using this code to add a dash('-') in a phone number after the 3rd and 4th number. The code is working just fine. My problem is that when I press backspace, I can't remove the dash. I can even add dots and I can delete them if I press backspace, but with dash it's just impossible.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MainActivity.headerName.setText("Verification");
phoneNumber = (EditText) getActivity().findViewById(R.id.phoneEditText);
int grup = 1;
phoneNumber.addTextChangedListener(new TextWatcher() {
int keyDel;
String a= phoneNumber.getText().toString();
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
phoneNumber.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KEYCODE_DEL) {
a = a.replace("-" , "");
phoneNumber.setText(a);
keyDel = 1;
}
return false;
}
});
if (keyDel == 0) {
int len = phoneNumber.getText().length();
if(len == 3 || len == 7) {
phoneNumber.setText(phoneNumber.getText() + "-");
phoneNumber.setSelection(phoneNumber.getText().length());
}
} else {
if(KeyEvent.isModifierKey(KEYCODE_DEL)) {
a = a.replace("-" , "");
phoneNumber.getText().toString().replace("-" , "");
phoneNumber.setText(a);
}
keyDel = 0;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
I'm guessing that your UI widget is formatting its text. So, after you remove the hyphen, the widget is putting it back.
I suggest you leave the widget alone. Instead, when you need to use the phone number, remove the formatting characters from the value.
String.replaceAll("[^\\d]", "")
You would use this code when retrieving the value from the widget for some external use. So, you might have a method
public String getPhoneNumberUnformatted() {...}
That returns only the digits of the widget's value.
I am new to Android Studio. I have gone through the official developer.android.com training and I decided to create a new and simple app called Grocery+ in which user will enter the price and quantity of particular item and app will display total sum.
I have done all UI based work then today I switched to programming. I am an experienced programmer of Java. I have also done all the work in it but:
1- my app crashes when I try to enter the first .
Then I have to enter any other value first then first value.
2- even after above hack my app doesn't display anything on 'grand total
Plese help :(((
package com.amostrone.akash.grocery;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int Quantity[] = new int[4];
static float Price[] = new float[4];
public static double total=0;
static TextView txtValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtValue = (TextView) findViewById(R.id.txtExample);
}
/////////// QUANTITY
public void input_Quantity(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity);
calc();
}
public void input_Quantity2(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity2);
Quantity[1] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity3(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity3);
Quantity[2] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity4(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity4);
Quantity[3] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity5(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity5);
Quantity[4] = Integer.parseInt(x.toString());
calc();
}
/////////////// Quantity
////////////// Price
public void input_Price(View view) {
EditText x = (EditText) findViewById(R.id.editPrice);
Price[0] = Float.parseFloat(x.toString());
calc();
}
public void input_Price2(View view) {
EditText x = (EditText) findViewById(R.id.editPrice2);
Price[1] = Float.parseFloat(x.toString());
calc();
}
public void input_Price3(View view) {
EditText x = (EditText) findViewById(R.id.editPrice3);
Price[2] = Float.parseFloat(x.toString());
calc();
}
public void input_Price4(View view) {
EditText x = (EditText) findViewById(R.id.editPrice4);
Price[3] = Float.parseFloat(x.toString());
calc();
}
public void input_Price5(View view) {
EditText x = (EditText) findViewById(R.id.editPrice5);
calc();
}
///////////// Price
/////////////// Calculate
public static void calc()
{
for(int i=0;i<=4;i++)
total += (Quantity[i] * Price[i]);
String str = Double.toString(total);
txtValue.setText(str);
}
////////////// Calculate }
Looking at your code it appears your are triggering EditText value get and calculation on click event (via xml). This does not work this way as they are triggered immediately. One of the approaches to solve this problem is to go the TextWatcher route. Check the below code built around that, I also refactored it a bit (should be lesser prone to memory leaks now):
public double mTotal;
private TextView mTextView;
private EditText[] mQuantityEditTexts = new EditText[5];
private EditText[] mPriceEditTexts = new EditText[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.txtExample);
mQuantityEditTexts[0] = (EditText) findViewById(R.id.editQuantity);
mQuantityEditTexts[1] = (EditText) findViewById(R.id.editQuantity2);
mQuantityEditTexts[2] = (EditText) findViewById(R.id.editQuantity3);
mQuantityEditTexts[3] = (EditText) findViewById(R.id.editQuantity4);
mQuantityEditTexts[4] = (EditText) findViewById(R.id.editQuantity5);
mPriceEditTexts[0] = (EditText) findViewById(R.id.editPrice);
mPriceEditTexts[1] = (EditText) findViewById(R.id.editPrice2);
mPriceEditTexts[2] = (EditText) findViewById(R.id.editPrice3);
mPriceEditTexts[3] = (EditText) findViewById(R.id.editPrice4);
mPriceEditTexts[4] = (EditText) findViewById(R.id.editPrice5);
for (int i = 0; i < 5; i++) {
mQuantityEditTexts[i].addTextChangedListener(mTextWatcher);
mPriceEditTexts[i].addTextChangedListener(mTextWatcher);
}
}
private TextWatcher mTextWatcher = 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) {
calc();
}
#Override
public void afterTextChanged(Editable s) {
}
};
public void calc()
{
try {
for (int i = 0; i <= 4; i++)
mTotal += Integer.parseInt(mQuantityEditTexts[i].getText().toString()) *
Double.parseDouble(mPriceEditTexts[i].getText().toString());
String str = Double.toString(mTotal);
mTextView.setText(str);
} catch (NumberFormatException e) {
Toast.makeText(this, "WTF! Enter valid numbers!", Toast.LENGTH_SHORT).show();
}
}
I have created custom edittext which does not hangs.
SearchTimerEditText
I have a simple golf scorecard app I'm developing. I have 9 textviews for now in which you enter a score hole by hole. When the score is entered the TextView background goes green if below par, red if above and white if even. IU have done this with TextWatchers.
I have a clear all Fields class, which clears all the textviews which always worked. But since I added the textwatchers for the scores my clear all textViews has stopped working. The program crashes.
This is my clear all TextView Code,
public class clearButtonListner implements OnClickListener {
private Activity activity;
public clearButtonListner(Activity activity){
this.activity = activity;
}
#Override
public void onClick(View v) {
TextView et1 = (TextView)this.activity.findViewById(R.id.EditTextScore1);
TextView et2 = (TextView)this.activity.findViewById(R.id.EditTextScore2);
TextView et3 = (TextView)this.activity.findViewById(R.id.EditTextScore3);
TextView et4 = (TextView)this.activity.findViewById(R.id.EditTextScore4);
TextView et5 = (TextView)this.activity.findViewById(R.id.EditTextScore5);
TextView et6 = (TextView)this.activity.findViewById(R.id.EditTextScore6);
TextView et7 = (TextView)this.activity.findViewById(R.id.EditTextScore7);
TextView et8 = (TextView)this.activity.findViewById(R.id.EditTextScore8);
TextView et9 = (TextView)this.activity.findViewById(R.id.EditTextScore9);
TextView ettotal = (TextView)this.activity.findViewById(R.id.editTextTotalScore);
et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
et5.setText("");
et6.setText("");
et7.setText("");
et8.setText("");
et9.setText("");
ettotal.setText("");
}
}
Example of one of my textWatchers,
public class textWatcher1 implements TextWatcher{
private Activity activity;
public textWatcher1(Activity activity){
this.activity = activity;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
int p1 = 5;
// Create my TextViews
TextView et1 = (TextView)this.activity.findViewById(R.id.EditTextScore1);
int s1 = (int)(Integer.parseInt(et1.getText().toString()));
if(s1 < p1){
et1.setBackgroundColor(Color.GREEN);
}
else if(s1 > p1){
et1.setBackgroundColor(Color.RED);
}
else if(s1 == p1){
et1.setBackgroundColor(Color.WHITE);
}
}
}
Any help would be great. The app crashes with throw new NumberFormatException("Invalid int: \"" + s + "\""); Exception.
That is because after erasing all your EditTexts with that Button click, your afterTextChanged(Editable s) callback is called. It is expecting a some content on your EditText but finds nothing, thus throwing that Exception, in parseInt().
You just have to add a condition for that code to execute, this is, only if the length of the text is bigger that 0. That way you will prevent the callback from making your app crash after clearing the EditTexts.
So, just add this line inside afterTextChanged(Editable s):
if(s.length()>0){
//your existing code
}
I advise you to only fill those EditTexts with content that is convertible to a number, or you will get that Exception again.
I have two text views and a EditText. In the TextViews are integers they are random generated. I want when the entry is correct in editText (Without OK button) the two textview change to new random integers.
I already have:
Random random1 = new Random(); int rand = random1.nextInt(100);
Random random2 = new Random();
int rand1 = random2.nextInt(100);
final TextView textview1 = (TextView)findViewById(R.id.textView1);
textview1.setText(String.valueOf(rand));
final TextView textview2 = (TextView)findViewById(R.id.textView2);
textview1.setText(String.valueOf (rand1));
final EditText edittext = (EditText)findViewById(R.id.editText1);
int f = -1; // or other invalid value
if (edittext.getText().toString().length() > 0) {
f = Integer.parseInt(edittext.getText().toString());
}
int answer = rand1 + rand;
if (f == answer) {
textview1.setText(rand++);
textview2.setText(rand1++);
}else {
System.out.println("!");
}
Thanks for your Help!
you can use the following block of code to check if the data in edit text has been set to correct value and now textview should be updated
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yourEditText = (EditText) findViewById(R.id.yourEditTextId);
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
yourEditText. ...
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
}