So, I want all of those variables to get the value after going through the OnClick method. When I put the log in the method they are ok, but outside... I know that they destroy because it's OnClick method and they are local but I don't know how to keep them. Please if you know how to help rewrite the code. Thanks!
package com.exemple.android.calendar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class NewEventActivity extends AppCompatActivity {
//step 1.A:create objects
public EditText DayEditText;
public EditText MonthEditText;
public EditText YearEditText;
public EditText StartingHourEditText;
public EditText StartingMinuteEditText;
public EditText EndingHourEditText;
public EditText EndingMinuteEditText;
public EditText Title;
public RadioGroup answer1;
public Button NewEventButton;
int day, month, year, s_hour, s_min, e_hour, e_min;
String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_event_page);
//Step 1.B: assign objects
DayEditText = findViewById(R.id.DayEditText);
MonthEditText = findViewById(R.id.MonthEditText);
YearEditText = findViewById(R.id.YearEditText);
StartingHourEditText = findViewById(R.id.StartingHourEditText);
StartingMinuteEditText = findViewById(R.id.StartingMinuteEditText);
EndingHourEditText = findViewById(R.id.EndingHourEditText);
EndingMinuteEditText = findViewById(R.id.EndingMinuteEditText);
Title = findViewById(R.id.TitleEditText);
answer1 = findViewById(R.id.Answer1);
NewEventButton = findViewById(R.id.CreateEventButton);
//Step 2: get data into variables
//Step 2.B: get data and assign
//PROBLEM: If we just extract, the code won't be run because there's nothing to extract yet. We need a conditional.
//SOLUTION: Create a condition for pressing the button, and then extract the variables when the button is pressed.
NewEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
title = Title.getText().toString();
day = Integer.parseInt(DayEditText.getText().toString());
month = Integer.parseInt(MonthEditText.getText().toString());
year = Integer.parseInt(YearEditText.getText().toString());
s_hour = Integer.parseInt(StartingHourEditText.getText().toString());
s_min = Integer.parseInt(StartingMinuteEditText.getText().toString());
e_hour = Integer.parseInt(EndingHourEditText.getText().toString());
e_min = Integer.parseInt(EndingMinuteEditText.getText().toString());
}
});
Log.i("INFO:",title+" "+day+" "+month+" "+year+" "+s_hour+" "+s_min+" "+e_hour+" "+e_min);
}
}
Your code is correct, it is just a understanding issue.
In fact, it's normal the Log method prints nothing because your variables are not set. The code inside the OnClick is called only if a click happens. Then, when click happens, your variables are set correctly.
Understood ?
Here is an example of TextWatcher
DayEditText = findViewById(R.id.DayEditText);
DayEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
day = Integer.parseInt(s.toString());
}
});
Do the same for each EditTexts you have
Related
This is a project in Codecademy.
I have a problem with the task : * Ensuring the app doesn’t crash when the equals button is pressed and one of the number boxes is empty.
When equals is pressed, before you do anything, ensure that the number boxes aren’t empty so an error doesn’t throw.
But with my code, the button equals is always false.
package com.codecademy.simplecalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText firstNumber;
EditText secondNumber;
RadioGroup operators;
RadioButton add;
RadioButton subtract;
RadioButton divide;
RadioButton multiply;
Button equals;
TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstNumber = findViewById(R.id.number1);
secondNumber = findViewById(R.id.number2);
operators = findViewById(R.id.Radio_Groupoperators);
add = findViewById(R.id.add);
subtract = findViewById(R.id.subtract);
multiply = findViewById(R.id.multiply);
divide = findViewById(R.id.divide);
equals = findViewById(R.id.equals);
result = findViewById(R.id.result);
equals.setEnabled(false);
/*firstNumber.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) {
equals.setEnabled(true);
}
});*/
equals.setOnClickListener(v -> {
int firstNumberValue = Integer.parseInt(firstNumber.getText().toString());
int secondNumberValue = Integer.parseInt(secondNumber.getText().toString());
int operatorButtonId = operators.getCheckedRadioButtonId();
Integer answer;
if (operatorButtonId == add.getId()) {
answer = firstNumberValue + secondNumberValue;
} else if (operatorButtonId == subtract.getId()) {
answer = firstNumberValue - secondNumberValue;
} else if (operatorButtonId == multiply.getId()) {
answer = firstNumberValue * secondNumberValue;
} else {
answer = firstNumberValue / secondNumberValue;
}
if (equals.getText().toString() == "") {
Toast.makeText(this, "Tap a number", Toast.LENGTH_SHORT).show();
} else {
equals.setEnabled(true);
}
result.setText(answer.toString());
});
}
}
Here's a simple answer, put these at the start of your onClickListener:
if (TextUtils.isEmpty(firstNumber.getText())) return;
if (TextUtils.isEmpty(secondNumber.getText())) return;
This will stop executing the function early if either firstNumber or secondNumber are empty strings.
Read more about this function here: https://developer.android.com/reference/android/text/TextUtils#isEmpty(java.lang.CharSequence)
So i am working on my university project nowadays and needed to use addTextChangedListener method on it. There weren't any problem at first but when i implement TextWatcher() it has a red underscore says that "invalid method declaration". And also override methods got "annotations are not allowed here". I dont understand what causes this problem so if you can help me i appreciate a lot.
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.text.TextWatcher;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
EditText activityTxt = (EditText) findViewById(R.id.txtActivity);
EditText whereTxt = (EditText) findViewById(R.id.txtWhere);
EditText whenTxt = (EditText) findViewById(R.id.txtWhen);
EditText withTxt = (EditText) findViewById(R.id.txtWith);
Button addBtn = (Button) findViewById(R.id.btnCreate);
mobileNumber.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mobileNumber.setError(null);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
mobileNumber.setError(null);
}
});
}
It looks like you forget to define: mobileNumber, this should be a textEdit. Your TextWatcher code has no problem.
Please also remove your unused import:
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
Optimize imports by pressing CTRL + ALT + O together
How to code in java for real time output which displayed on the screen,as soon as user inputs some value with keyboard, with out a calculate button in activity in a simple conversion program? I have given the code below. In that it takes one input value and "FROM" and "TO" to convert the value and showed in the display with press of "calculate" button
Now I want to eliminate the "calculate" button and as soon as user inputs the numbers want to show the answer to the display
My code given below. Please let me know any additional information required
package sujaynambiar.textilecalculation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class LengthConverter extends AppCompatActivity {
private Spinner spinner11, spinner21;
private EditText from;
private TextView to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lenght_converter);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit1);
from = (EditText) findViewById(R.id.InputEditText1);
to = (TextView) findViewById(R.id.OutputTextView1);
spinner11 = (Spinner) findViewById(R.id.spinner11);
List<String> list1 = new ArrayList<String>();
list1.add("Kilometer");
list1.add("Meter");
list1.add("Centimeter");
list1.add("Millimeter");
list1.add("Feet");
list1.add("Yard");
list1.add("Inch");
list1.add("Mile");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner11.setAdapter(dataAdapter1);
spinner21 = (Spinner) findViewById(R.id.spinner21);
List<String> list2 = new ArrayList<String>();
list2.add("Kilometer");
list2.add("Meter");
list2.add("Centimeter");
list2.add("Millimeter");
list2.add("Feet");
list2.add("Yard");
list2.add("Inch");
list2.add("Mile");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner21.setAdapter(dataAdapter2);
}
public void onClick(View v)
{
int index1 = spinner11.getSelectedItemPosition();
int index2 = spinner21.getSelectedItemPosition();
double value = 0;
if (from.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(), getResources().getString(R.string.toastmessage1),
Toast.LENGTH_LONG).show();
else {
value = Double.parseDouble(from.getText().toString());
}
//From Kilometer
if (index1 == 0 && index2 == 0 )//N
{
double result = value*1;
to.setText(result+"");
}
You are looking for a text change listener.
from.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) {
calculateNewResult(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
You may also want to use an item select listener on the spinners.
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
updateTheCalculation();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Hey guys and gals I am having trouble figuring out the process and method to best solve my problem.I have an app in which user created text is shown in a secretive font/language, while English(non-secretive) text is displayed in the textview.
JAVA
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.view.KeyEvent;
public class MainActivity extends ActionBarActivity {
TextView tv;
EditText et;
private Button convert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Loading our AvianKingdom Codex Font
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/WWAvianKingdom-Regular.ttf");
//Text view label
tv = (TextView) findViewById(R.id.CustomFontText);
et = (EditText) findViewById(R.id.CodexMessage);
//Applying the font
et.setTypeface(tf);
//Convert the text
et.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
String inputText = et.getText().toString();
tv.setText(inputText);
return true;
default:
break;
}
}
return false;
}
});
}
In my app I am trying to update a textview as the user enters text, but so far I have only been able to change upon click/press of a button.My question is,
How do I update TextView with EditText in realtime using java inside Android Studio?
I want to do this before I hit the send/enter button, during the users type phase. What is the best solution in your opinion? I have looked up TextWatcher/KeyListener/KeyClick but being new to Java doesn't help me decide or understand completely.
FIGURED IT OUT!!!
I ended up researching a lot and found a very helpful blog post. here is the answer
package com.christianlopez.helloworld;
//De-Raptor-Codex Android Prototype
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.support.v4.view.MenuItemCompat;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.TextView;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.graphics.Typeface;
import android.content.Intent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
public class MainActivity extends ActionBarActivity {
TextView CodexTV;
EditText CodexET;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Loading our AvianKingdom Codex Font
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/WWAvianKingdom-Regular.ttf");
//Text view label
CodexET = ((EditText) findViewById(R.id.CodexMessage));
//REAL-TIME Textview change
CodexET.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) { //Convert the Text to String
String inputText = CodexET.getText().toString();
CodexTV = ((TextView) findViewById(R.id.CustomFontText));
CodexTV.setText(inputText);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
});
//Applying the font
CodexET.setTypeface(tf);
//Screenshot our Codex'ed Image
CodexET.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_CENTER:
doShare(getDefaultIntent());
captureScreen();
case KeyEvent.KEYCODE_ENTER:
doShare(getDefaultIntent());
captureScreen();
default:
break;
}
}
return false;
}
});
}
The answer begins at e.addtextChanged Listener. This sets up the app to be paying attention to any changes in the EditText and then I take that into a string, and relay it back to Textview in realtime.
Just trying to keep your answer short...It is the .addTextChangedListener method and inside that we're coding in afterTextChanged method.
CodexET.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) { //Convert the Text to String
String inputText = CodexET.getText().toString();
CodexTV = ((TextView) findViewById(R.id.CustomFontText));
CodexTV.setText(inputText);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Does not do any thing in this case
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Does not do any thing in this case
}
});
I just need som minor help now. The app runs great but when you enter for ex. USD, 2 TO SEK it results 13,38. But if i change the amount to 3 nothing happens. I would have to change the currencys back and forth to make a change. I would like the app to change the result as soon as i change the value. Please help!:)
package com.example.currencyconverter;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private String [] currency_name;
private ArrayAdapter<String> adapter;
private Spinner spin1, spin2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpTheSpinners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
private void setUpTheSpinners() {
currency_name = getResources().getStringArray(R.array.currency_name);
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, currency_name);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OnItemSelectedListener listener = new CurrencySelectedListener();
spin1 = (Spinner)findViewById(R.id.spinner1);
spin1.setAdapter(adapter);
spin1.setOnItemSelectedListener(listener);
spin2 = (Spinner)findViewById(R.id.spinner2);
spin2.setAdapter(adapter);
spin2.setOnItemSelectedListener(listener);
}
private void calculateSum() {
String [] rates = getResources().getStringArray(R.array.currency_rate);
int index1 = spin1.getSelectedItemPosition();
int index2 = spin2.getSelectedItemPosition();
double rate1 = Double.parseDouble( rates[index1] );
double rate2 = Double.parseDouble( rates[index2] );
EditText editAmount = (EditText) findViewById(R.id.editText1);
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
double amount = Double.valueOf(editAmount.getText().toString());
double totalRate = amount * rate1 / rate2;
TextView totalRateText = (TextView)findViewById(R.id.editText2);
totalRateText.setText("" + totalRate);
}
}
private class CurrencySelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
calculateSum();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
Your editAmount.getText().toString() value is NULL(empty). And you still trying to convert this value into DOUBLE so you got NumberFormatException .
Check editText value before parsing like:
if(!editAmount.getText().toString().equals(""))
{
//Do your job
}
Or another way is
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
//Do your job
}