Live txt field send without button - android

I'm trying to use a toggle button to switch between English -> Morse code and Morse code -> English. At this moment, I have to press the toggle button everytime I want the inputted data to be converted and this is not good. I want the toggle button only to be pressed once as desired to select to what it wants to translate to, and then while the user inputs data into the txt field, it will translate it as the user inputs data. Is this possible? And will this cause the app to lag?
If this will lag I'd like something else then.
A switch like the toggle button, to again choose to which one it needs to translate to. And then use to button to convert. This is somewhat possible now, but I need to click on the toggle button to translate, while I want to select the convert button to translate, and the toggle button to choose between English -> Morse code and Morse code -> English.
Here is some code I have for the toggle button:
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleEnMo_Button);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// to English
Toast.makeText(MainActivity.this, toggle.getText(), Toast.LENGTH_SHORT).show();
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toEnglish(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
} else {
// to Morse
Toast.makeText(MainActivity.this, toggle.getText(), Toast.LENGTH_SHORT).show();
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toMorse(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
}
}
});
And the code I use for radio buttons and convert button which works:
button_convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// show radio button text
int selectId = radioMorseGroup.getCheckedRadioButtonId();
radioMorseButton = (RadioButton) findViewById(selectId);
if (selectId == R.id.toEnglish) {
Toast.makeText(MainActivity.this,
radioMorseButton.getText(), Toast.LENGTH_SHORT).show();
// to english
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toEnglish(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
} else if (selectId == R.id.toMorse) {
// to morse
Toast.makeText(MainActivity.this,
radioMorseButton.getText(), Toast.LENGTH_SHORT).show();
if (edit_convert.getText().length() != 0) {
morseCode.setEnInput(edit_convert.getText().toString());
String txtToEnglish = morseCode.getEnInput();
morseCode.setMorseInput(morseCode.toMorse(txtToEnglish));
String txtToMorse = morseCode.getMorseInput();
txtEnglish.setText(txtToEnglish);
txtMorse.setText(txtToMorse);
} else {
txtEnglish.setText("Text field empty");
}
}
}
});

I believe you are asking about intercepting user input as they type into a text field. You can use a TextWatcher. Here's some sample code that demonstrates this.
EditText mInputEt;
public void onCreate(Bundle savedInstanceState){
...
mInputEt.addTextChangedListener(mMyTextWatcher);
}
private TextWatcher mMyTextWatcher = 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) {
//take user input here and do something with it, like your translations
}
#Override
public void afterTextChanged(Editable s) {
}
};
Now to your question regarding lag, it shouldn't lag as long as all your intensive operations are executed in the background, off the main thread.

Related

How to change the background of many images when user entered a text in EditText in Android

I have a program that has 10 images. I want to change the background of each image when the user enters valid text in editText. So basically if user enters valid text in the editText it will change the first image (image 1). If the user enters text again in editText it should change image 2 etc. until image 10.
I have tried to create a list of images and retrieve every element in the image.
I don't know if my logic is wrong
The images are stamp1, stamp2, stamp3, stamp4 ....stamp12
final String Entercode = codeNumber.getEditableText().toString().trim();
Toast.makeText(getApplicationContext(),Entercode,Toast.LENGTH_SHORT).show();
if (Entercode.equals("sweet")){
for (int i = 0; i < stampImageList.size(); i++) {
Object obj = stampImageList.get(i);
stampImageList = new ArrayList();
stampImageList.add(stamp1);
stampImageList.add(stamp2);
stampImageList.add(stamp3);
stampImageList.add(stamp4);
stampImageList.add(stamp5);
stampImageList.add(stamp6);
stampImageList.add(stamp7);
stampImageList.add(stamp8);
stampImageList.add(stamp9);
stampImageList.add(stamp10);
stampImageList.add(stamp11);
stampImageList.add(stamp12);
if (obj == stampImageList.get(2)) {
// stamp4.setBackgroundResource(R.drawable.earned_stamp);
stamp3.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
} else if (obj == stampImageList.get(3)) {
stamp5.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
}
}
} else{
AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
alert.setIcon(R.drawable.logo);
alert.setTitle("Validation results");
alert.setMessage("validation failed");
}
You should use TextWatcher to EditText.In afterchange method you compare with values.
EditText et = (EditText)findViewById(R.id.editText);
Log.e("TextWatcherTest", "Set text xyz");
et.setText("xyz");
et.addTextChangedListener(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) {
Log.e("TextWatcherTest", "afterTextChanged:\t" +s.toString());//Compare here with stamp1 or like that
}
});
#steve, here I have prepared a code for 10 Drawable Images in your project.
public class Pictures_Activity_stack extends AppCompatActivity {
private String TAG= "Pictures_Activity---";
private ImageView picture;
private EditText text;
private Button validate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pictures_stack);
picture = (ImageView)findViewById(R.id.picture); //imageview where your picture changes
text = (EditText) findViewById(R.id.text);//edittext where you input text
validate = (Button) findViewById(R.id.button);//button to validate the text and change picture accordingly
// array to store your drawable images
final int pictures[] = {
R.drawable.firstimage,
R.drawable.secondimage,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10
};
// click the button to set the image
validate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String input = text.getText().toString(); //input from edittext
if (input.equals("first")) {
picture.setImageResource(pictures[0]); //set first image in array if input=first
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
else if (input.equals("second")) {
picture.setImageResource(pictures[1]);//set first image in array if input=secind
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
// else if (input.equals("third")) {
// // and so on for other string values...
// .................................
// }
else
{
// if your input does not matches any string do this
Toast.makeText(getBaseContext(),"NO MATCHED STRING",Toast.LENGTH_SHORT).show();
}
}
});
}
}
The above code set images according to input in edit Text, when button is clicked.

How to check EditText isEmpty in Android

I want to create a login page, I used EditText to insert user info. I want to check EditText to see if it is Empty Invisible login Button, when inserted any character with user visible Login Button.
I tried the code shown below, but it did not not work for me :
//Show Login Button
String login_phoneString = login_PhoneText.getText().toString().trim();
if (login_phoneString.isEmpty()) {
login_image.setVisibility(View.INVISIBLE);
} else {
login_image.setVisibility(View.VISIBLE);
}
When EditText is empty, the button is invisible, and when set character in EditText again the login button is not shown.
How can I fix this problem ?
You want to show/hide the Login button base on the text of EditText so you need to listen for changing in EditText by use TextWatcher.
Use this code inside onCreate() method
login_PhoneText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String login_phoneString = login_PhoneText.getText().toString().trim();
if (login_phoneString.isEmpty()) {
login_image.setVisibility(View.INVISIBLE);
} else {
login_image.setVisibility(View.VISIBLE);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
Using trim()
if(et.getText().toString().trim().length() == 0) //empty
Using TextUtils
if(TextUtils.isEmpty(et.getText().toString().trim()) //Empty
Using isEmpty()
if(et.getText().toString().isEmpty()) //Empty
EDIT
You can do this :
//Show Login Button
String login_phoneString = login_PhoneText.getText().toString().trim();
if (TextUtils.isEmpty(login_phoneString) {
login_image.setVisibility(View.INVISIBLE);
} else {
login_image.setVisibility(View.VISIBLE);
}
Try to check like this way
EditText edt = (EditText) findViewById(R.id.edittext);
String abc = edt.getText().toString();
if (abc.matches("")) {
Toast.makeText(this, "enter something", Toast.LENGTH_SHORT).show();
login_image.setVisibility(View.INVISIBLE);
return;
}
else
{
login_image.setVisibility(View.VISIBLE);
}
String login_phoneString = login_PhoneText.getText().toString().trim();
if (login_phoneString.equals("")) {
login_image.setVisibility(View.GONE);
} else {
login_image.setVisibility(View.VISIBLE);
}
Use View.GONE instead of INVISIBLE. when INVISIBLE it is still clickable.
Use TextUtils.isEmpty():
if (TextUtils.isEmpty(yourEditText.getText().toString())) {
//Empty
} else {
//Not empty
}

(Android) Enable button only when all login fields are not giving an error

been looking for a previous answer for this but can't seem to find an android version of it...
I'm making a login page for an app, and I've got 3 input fields (First name, last name, email) and a text watcher to tell the user if there's an error in their input ((e.g. nothing there/too long/not a valid email). I'm trying to make the log in button disabled until no errors are showing, but I can't seem to sort it. I'm very new to android, just been working from scraps of tutorials here and there really... I've tried setting a boolean for each input value that sets to false when the input is bad/true when it's acceptable, and something to check if all 3 are true or not to enable/disable the button but that doesn't seem to work...
In the emulator, the button doesn't disable at all and I've got warnings that the booleans I made are always true even though I've given instances to make them false, and defined them as false at the start...
Here's my java class at the moment:
public class Login extends Activity implements OnClickListener, TextWatcher {
EditText firstName;
EditText lastName;
EditText eMail;
ImageButton Begin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initialiseUI();
}
private void initialiseUI() {
eMail = (EditText)findViewById(R.id.edit_email);
eMail.addTextChangedListener(this);
firstName= (EditText)findViewById(R.id.edit_firstname);
firstName.addTextChangedListener(this);
lastName= (EditText)findViewById(R.id.edit_surname);
lastName.addTextChangedListener(this);
Begin= (ImageButton) findViewById(R.id.Beginbutton);
Begin.setOnClickListener(this);
}
boolean name=false;
boolean surname=false;
boolean email=false;
boolean isEmailValid(CharSequence eMail) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(eMail)
.matches();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) {
Is_Valid_Email(eMail);
Is_Valid_Name(firstName);
Is_Valid_Surname(lastName);
Is_Login_Valid();
}
public void Is_Valid_Name(EditText firstName) {
if (firstName.getText().toString().trim().isEmpty()){
firstName.setError("Enter Name");
name=false;}
else if (firstName.getText().toString().length()>20){
firstName.setError("Name too long!");
name=false;}
else if (firstName.getText().toString().length()>1){
firstName.setError(null);
name=true;}
}
public void Is_Valid_Surname(EditText lastName){
if (lastName.getText().toString().trim().equalsIgnoreCase("")){
lastName.setError("Enter Surname");
surname=false;}
else if (lastName.getText().toString().length()>20){
lastName.setError("Surname too long!");
surname=false;}
else if (lastName.getText().toString().length()>1){
lastName.setError(null);
surname=true;}
}
public void Is_Valid_Email(EditText eMail) {
if (eMail.getText().toString().trim().equalsIgnoreCase("")) {
eMail.setError("Enter e-mail");
email=false;}
else if (!isEmailValid(eMail.getText().toString())) {
eMail.setError("Invalid Email Address");
email=false;}
else if (isEmailValid(eMail.getText().toString())) {
email=true;}
}
public void Is_Login_Valid() {
if (name=true){
if (surname=true){
if (email=true){
Begin.setEnabled(true);
}
else if (email=false){
Begin.setEnabled(false);
}
}
else if(surname=false){
Begin.setEnabled(false);
}
}
else if (name=false){
Begin.setEnabled(false);
}
}
/** Called when the user clicks the Login button */
public void onClick(View v) {
Intent intent = new Intent(Login.this, question_1.class);
startActivity(intent);
}
}
Please check setClickable(false)
http://developer.android.com/reference/android/view/View.html#setClickable%28boolean%29
I wouldn't use variables for check status. Have you tried what happens when a screen rotation? This might be chaos.
I recommend you to check your status everytime the text changes:
public void Is_Login_Valid() {
if(Is_Valid_Name(firstName) && Is_Valid_Surname(lastName) && Is_Valid_Email(eMail)){
Begin.setEnabled(true);
}else{
Begin.setEnabled(false);
}
I removed the name, surname, email booleans & Is_Login_Valid terms entirely and copied the acceptable conditions from Is_Valid_Name, Is_Valid_Surname and Is_Valid_Email into an if statement within the button's onClick term as below, and it seems to work fine now:
public void onClick(View v) {
if ((firstName.getText().toString().length() >= 1)
&& (firstName.getText().toString().length() < 20)
&& (lastName.getText().toString().length() >= 1)
&& (lastName.getText().toString().length() < 20)
&& (isEmailValid(eMail.getText().toString())))
{Intent intent = new Intent(Login.this, question_1.class);
startActivity(intent);}
else{ //TODO Login failed animation or popup
}
}

How to Check whether a value is entered in editexts before submitting?

I have around 5 edittexts.When i click submit button,it has to check whether all fields are entered or not.Along with it if any value is not entered,the focus has to go to that desired edittext.If there are many editexts empty,then the focus has to go in top down order.I have used seterror method but when i type in that editext the error msg is not going.After entering values the focus is not going to the next edittext.how to solve this issue?
caseno,dateloss,policy_rep,reg_book,Dri_lic are the different editexts used.I have written code for one editext below
caseno.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasfocus)
{
if(!hasfocus && caseno.getText().length()==0)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run() {
//ev2.clearFocus();
dateloss.clearFocus();
policy_rep.clearFocus();
reg_book.clearFocus();
Dri_lic.clearFocus();
caseno.requestFocus();
caseno.setError("Enter this field");
}
}, 100);
}
}
});
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(caseno!=null||dateloss!=null||policy_rep!=null||reg_book!=null||Dri_lic!=null)
{
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Android provides a setError() method for this:
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
}
Define a method to check whether your EditTexts have valid data:
private boolean validateEditTexts()
{
boolean valid = true;
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
valid = false;
}
// Similarly check all your EditTexts here and set the value of valid
......
......
return valid;
}
To validate all your EditTexts, call validateEditTexts() which will return true or false accordingly.
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(validateEditTexts()){
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Try this. This will work.
Check this:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText is empty
}
}
Maintain array of EditText references: Like
EditText[] allEts = { caseno, dateloss, policy_rep, reg_book, Dri_lic };
Write the below code in onClick of submit button:
for (EditText editText : allEts) {
String text = editText.getText().toString();
if (text.length() == 0) {
editText.setError("enter this field");
editText.requestFocus();
break;
}
}
And, implement addTextChangedListener for all edittexts to clear the error after entering the text.
caseno.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Editable text = caseno.getText();
if (caseno.getError() != null && text != null
&& text.length() > 0) {
caseno.setError(null);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Use this on your button click
if(!textView1.toString().isEmpty() && !textView2.toString().isEmpty() && ...)
{
............
}
1) create this method
public static boolean isNullOrEmpty(String input) {
return input == null || input.isEmpty();
}
2) send data to it for validation
boolean answer = isNullOrEmpty(editText.gettext().toString());
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(caseno.getText().toString()))
{
caseno.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(dateloss.getText().toString()))
{
dateloss.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
}
Currently this setup is working for me...Thnks those who answered

why i get invalid integer exception each time i click my button?

I have is an android class. I get some data from get extra which are displayed fine. All of the data is strings. Here is my class:
package adapter;
public class AddToCart extends Activity {
EditText quantity=null;
TextView total=null;
TextView name=null;
TextView price=null;
TextView ava=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Intent intent = getIntent();
final String itemprice = intent.getStringExtra("price");
String itemname = intent.getStringExtra("item");
final String itemava = intent.getStringExtra("ava");
int imagehandler = intent.getIntExtra("image", 0);
Log.e("image handler",imagehandler+"");
name = (TextView)findViewById(R.id.textView2);
price = (TextView)findViewById(R.id.textView4);
total = (TextView)findViewById(R.id.textView7);
ava = (TextView)findViewById(R.id.textView9);
quantity = (EditText)findViewById(R.id.editText1);
Button addtocart = (Button)findViewById(R.id.button1);
ImageView imageview=(ImageView)findViewById(R.id.imageView1);
name.setText(itemname);
price.setText(itemprice);
ava.setText(itemava);
imageview.setImageResource(imagehandler);
addtocart.setOnClickListener(new OnClickListener() {
int currentava = Integer.parseInt(itemava);
#Override
public void onClick(View v) {
try{
String checked = quantity.getText().toString();
if(checked==null) {
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
else {
int x=0;
double y=0.0;
x = Integer.parseInt(quantity.getText().toString());
y = Double.parseDouble(itemprice);
Log.e("x",x+"");
Log.e("y",y+"");
double totalprice=x*y;
total.setText(totalprice+"");
Toast.makeText(AddToCart.this,"your item added succesfully !", Toast.LENGTH_LONG).show();
}
}//view
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
As you can see that quantity is edit text and when some number inserted into it multiply it by price value and show the total price in text view which works just fine when i click the button, but what I really need to do is to handle this functionality with two if statements. First if the edit text for quantity was empty and the user click the button I want a toast to be displayed to says : "please enter a value for quantity" and the other statement that if quantity larger than available to refuse the value and also toast : "please enter value less than available" It doesn't work as I have an invalid integer value exception. Please what is wrong with my code and how can i handle the previous issues?
Declare "itemava" globally and try again
Looks to me where you use ,
if(checked==null){
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
that there are 2 alternatives to this.
1.
Probably the easiest
if(checked==null || quantity.isEmpty()){
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
The addition is the || quantitiy.isEmpty()
I had tons of issues trying to solve for cases when the string was empty and this is the best way and also uses built in functions that are very easy to use.
2.
Not quite as easy but probably the better bet
Rather than checking to see if the string itself is null, it would be best to check if the editText has been changed at all, and then if it has been changed, make sure that it was changed to a non-empty string, like in 1. To do this add a textChangedListener like so:
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
//set a textChangedFlag to true
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
This will require a boolean flag that should always be initialized to false. Then after setting the flag to true in the onTextChanged method, you should still double check the string, just to be safe (this may be overkill, but I tend to error on the side of caution) by using a similar method as in 1.
if(textChangedFlag && !(checked == NULL || quantity.isEmpty())){
//do your math here
}
else{
Toast.makeText(AddToCart.this,"please enter a valid quantity", Toast.LENGTH_LONG).show();
}
Text can still be empty... Try something like this:
import android.text.TextUtils;
String value = quantity.getText().toString();
if (TextUtils.isEmpty(value)) {
// enter a value toast
} else if (!TextUtils.isDigitsOnly(value)) {
// must be numeric toast (notice the exclamation mark in condition)
} else {
int valueInt = Integer.parseInt(value);
// ...
}

Categories

Resources