Android Studio: Adding two numbers wihout a button - java

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

Related

toggle.setchecked inside a onTextChanged event

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.

Using TextChanged listener on two relative text fields

This is my first question. I have very basic java training and I am developing a simple app in Android Studio right now. The app is a temperature converter that reads one TextField and after applying a method, it shows output in the other TextField in Realtime.
So, here's what I'm doing:
A screenshot of ActivityMain.xml
The code:
public class MainActivity extends AppCompatActivity {
private EditText tc;
private EditText tf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tc = (EditText) findViewById(R.id.TempInC);
tf = (EditText) findViewById(R.id.TempInF);
So far so good. tc gets the input from Temperature in Celsius TextField, and tf gets input from Temperature in Fahrenheit TextField.
After that, I have:
tc.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
String strTempCval = null;
strTempCval = tc.getText().toString();
if (strTempCval.isEmpty()) {
tf.setText(null);
} else {
double tempCval = Double.parseDouble(strTempCval);
double ctofVal = toF(tempCval);
String fResult = String.valueOf(ctofVal);
tf.setText(fResult);
}
}
});
This part takes the tc input, and converts it to fahrenheit by using toF method (in the MainActivity class, at the end), and show it in the tf TextField.
The next thing I want to do is the exact reverse of the above code, with the tf input, so here it goes:
tf.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
String strTempFval = tf.getText().toString();
if (strTempFval.isEmpty()) {
tc.setText(null);} else {
double tempFval = Double.parseDouble(strTempFval);
double ftocval = toC(tempFval);
String resultC = String.valueOf(ftocval);
tc.setText(resultC);
}
}
});
}
Now the problem is
...that if I'm using one of the above (either the one that converts c to f, or the one that converts f to c.), it works just fine (For example, if I comment out/disable one of these blocks). However, if I try to use both of the above functions simultaneously at the same time, the application crashes. Obviously because both TextChangedListeners are trying to manipulate/interact with each other.
Although, if required, the next part of the code is here: (The methods)
public double toC (double fVal){
double cResult;
cResult=(fVal-32)*5/9;
return cResult;
}
public double toF (double cVal){
double fResult = (cVal*9/5)+32;
return fResult;
}
//MainActivity ends here.
Whew, so that's all the source code there. I hope someone can help me because I am very frustrated at this as I can't use OnKeyListener (intended for hard input). Any help would be highly appreciated as I have been stuck at it for days! A bundle of thanks in advance for anyone who is willing to help me!
you will be getting a stackOverflowException which is because it goes into infinite loop
so use hasFocus() like this to solve your problem, as only the EditText beings edited by the user will have focus. do this for both EditTexts
tf.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
if(tf.hasFocus()) {
String strTempFval = tf.getText().toString();
if (strTempFval.isEmpty()) {
tc.setText(null);
} else {
double tempFval = Double.parseDouble(strTempFval);
double ftocval = toC(tempFval);
String resultC = String.valueOf(ftocval);
tc.setText(resultC);
}
}
}
});
}

Dynamic calculation of a TextView that is linked to a seris of buttons

I'm trying to create this flow on an application I'm building. I am having a little bit of trouble getting the TextView to be friendly with any kind of formula/conditions. Any suggestions on how I can get the TextView to output the result dynamically through my text watchers? Thanks in advance!
Text Views
//------------------DISPLAY-----------------\\
netsale = (TextView)findViewById(R.id.netsale_input);
//--------------WAIT ASSISTANT--------------\\
waMain = (TextView)findViewById(R.id.txt_wa_main);
waSplit = (TextView)findViewById(R.id.txt_wa_split);
Clear Button
public void clr_Clicked(View sender){
netsale.setText("0");
isempty=true;
}
Number Pad
static boolean isempty=true;
public void num_Clicked(View sender){
Button bt=(Button)sender;
if(netsale.getText().length()>5)return;
if(isempty)
{
if(bt.getText().toString().equals("0"))return;
netsale.setText(bt.getText());
isempty=false;
}
else
{
netsale.append(bt.getText());
}
}
Text Watchers
private TextWatcher filterTextWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
}
When you click on a button, lets say "7", you should append that value to the TextView by utilizing setText(CharSequence);
So at first if your TextView is blank (""), when you click the 7, it should result in your TextView showing "7"

Values of EditText fields are changed depends on each other

I'm trying to build temperature converter (F -> C and C -> F).
I have 2 ET fields. when user types in one, the other displays converted value and vice verse.
I understand that similar programs has been build already, but I couldn't find solution.
It works fine for one field, but app closes when I try to edit the other one.
Here is my piece of code:
public class Temp extends Activity implements OnClickListener, OnFocusChangeListener {
private EditText temp_f, temp_c;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.temp);
temp_f = (EditText) findViewById(R.id.temp_f_inp);
temp_c = (EditText) findViewById(R.id.temp_c_inp);
temp_c.setOnFocusChangeListener((OnFocusChangeListener) this);
temp_f.setOnFocusChangeListener((OnFocusChangeListener) this);
}
private TextWatcher tempc = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (temp_c.getText().length() == 0)
{
temp_f.setText("");
} else {
float convValue = Float.parseFloat(temp_c.getText()
.toString());
conv_f = ((convValue - 32) * 5 / 9);
temp_f.setText(String.valueOf(new DecimalFormat(
"##.###").format(conv_f)));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {
}
};
private TextWatcher tempf = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,int before, int count) {
// TODO Auto-generated method stub
if (temp_f.getText().length() == 0)
{
temp_c.setText("");
} else {
float convValue = Float.parseFloat(temp_f.getText()
.toString());
conv_c = ((convValue * 9) / 5 + 32);
temp_c.setText(String.valueOf(new DecimalFormat(
"##.###").format(conv_c)));
}
#Override
public void beforeTextChanged(CharSequence s, int start,int count, int after) {}
#Override
public void afterTextChanged(Editable s) {
}
};
#Override
public void onFocusChange(View v, boolean hasFocus) {
if ((v == findViewById(R.id.temp_c_inp)) && (hasFocus==true)) {
temp_c.addTextChangedListener(tempc);
}
else if((v == findViewById(R.id.temp_f_inp)) && (hasFocus==true)){
temp_f.addTextChangedListener(tempf);
}
}
it seems like onTextChanged still holds the values of the first ET that has been modified and when I try to edit the other ET fields, it throws an error.
Any help would be greatly appreciated!
Thank you!
You could try this:
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (v.equals(findViewById(R.id.temp_c_inp))) {
if(hasFocus){
temp_c.addTextChangedListener(tempc);
}else{
temp_c.removeTextChangedListener(tempc);
}
}
else if(v.equals(findViewById(R.id.temp_f_inp))){
if(hasFocus){
I temp_f.addTextChangedListener(tempf);
}else{
temp_f.removeTextChangedListener(tempf);
}
}
}
I haven't tried the code by myself, but I hope it could help you
Logic seems to be a problem.
What I would do is,
1. On text change, do nothing (or just check for valid input values)
2. On focus change, do conversion and populate other text field.
Also, you have some #Override functions which are essentially null functions. Why override?

To grab text from Edit text and highlight this text in Current text view

I working on module to search grab text from edit text and search it into current text view. If present highlight this text in current text view. I also googled for this code but didn't found any relevant answer.
tv=(TextView) mView.findViewById(R.id.detailsText);
edit_text=(EditText)findViewById(R.id.searchText);
edit_text.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hightLightText(tv, s.toString());
}
});
}
void hightLightText(TextView textView, String searchString){
try{
String s=getResources().getString(R.string.firstpage);
String withHighLightedText = s.replaceAll(searchString, "<font color='red'>"+searchString+"</font>");
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
}catch(Exception ex){
}
}
HTML tag formatting within TextView is very limited.
<b>Bold</b> and <i>Italic</i>
do work, but
<font color>
sadly does not.
Use Spannable instead to highlight to portions of text you want.
Here is an example for making selected text Italic within an EditText View: Is there any example about Spanned and Spannable text
call the below function for highlighting.
public void hightLightText(TextView textView, String searchString) {
String s = textView.getText().toString();
SpannableString str = new SpannableString(s);
if (searchString != null && !searchString.equalsIgnoreCase("")) {
int startIndex = 0;
while (true) {
startIndex = s.indexOf(searchString, startIndex);
if (startIndex >= 0) {
str.setSpan(new BackgroundColorSpan(Color.YELLOW),
startIndex, startIndex + searchString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
startIndex++;
} else {
break;
}
}
}
textView.setText(str);
}
EditText edit_text;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edittest);
tv=(TextView) findViewById(R.id.detailsText);
edit_text=(EditText)findViewById(R.id.searchText);
edit_text.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hightLightText(tv, edit_text.getText().toString().trim());
}
});
}
void hightLightText(TextView textView, String searchString){
try{
String s=getResources().getString(R.string.app_name);
String withHighLightedText = s.replaceAll(searchString, "<font color='red'>"+searchString+"</font>");
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(withHighLightedText), TextView.BufferType.SPANNABLE);
}catch(Exception ex){
}
}
In your code just change the bellow method
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hightLightText(tv, edit_text.getText().toString().trim());
}

Categories

Resources