I have a problem regarding Edit Text in Android.
I have a field named Username :
I want that whenever someone writes a username with a space e.g "Gaurav Arora". Then it should raise a toast or error on the login button press.
I did in this way - I simply stopped the effect of space bar with the help of a text watcher as-
public static TextWatcher getNameTextWatcher(final TextView agrTextView) {
TextWatcher mTextWatcherName = new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
String result = agrTextView.getText().toString().replaceAll(" ", "");
if (!agrTextView.getText().toString().equals(result)) {
agrTextView.setText(result);
}
}
}
But this has not solved my purpose. I just want to implement whenever the person uses a username with space it should accept the space but on the press of login button it should raise a toast
Thanks
Just check if your edit text contains blank space or not.
Use the following code in the onClick() event of the Button.
if (agrTextView.getText().toString().contains(" ")) {
agrTextView.setError("No Spaces Allowed");
Toast.makeText(MyActivity.this, "No Spaces Allowed", 5000).show();
}
Try this..
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String result = agrTextView.getText().toString();
if(result.contains ("\\s"))
Toast.makeText(getApplicationContext(), "Space ", Toast.LENGTH_LONG).show();
}
});
Simply do this:
TextView.getText().toString().contains(" ");
String question = txtNote.getText().toString();
if(question.trim().length() > 0){
Log.i("LOG", "Has value");
}else{
Log.i("LOG", "don't has value");
}
use trim() method to remove all spaces and then check for empty
if ( !edtText.getText().toString().trim().isEmpty()) {
//the EditText is not Empty
}
Also you can block entering space bar in username, or can give toast or snack on entering space in username .
Can refer this link might be helpful for you Block entering space in edittext.
Let me know if any concern.
Related
I have an anctivity with 6 EditText... the activity is working good, but I need to click on each EditText to fill it...
How can I make enter key change the focus to another EditText?
What I've already tried
1. I already setted OnKeyListener on every EditText.
switch (v.getId()) {
case R.id.editText1:
activity.findViewById(R.id.editText2).requestFocus();
return true;
case R.id.editText2:
activity.findViewById(R.id.editText3).requestFocus();
return true;
case R.id.editText3:
activity.findViewById(R.id.editText4).requestFocus();
return true;
.
.
.
}
But, when I click on enter key, before the focus change to another EditText, a new line is create on previous EditText.
2. I've add android:singleLine="true" to every EditText. It isn't work on EditText with inputType="number"
You can add imeOptions attribute for EditText's in your xml:
android:imeOptions="actionNext"
But not forget to specify inputType:
For example, android:inputType="text"
For more details check this question - Move to another EditText when Soft Keyboard Next is clicked on Android
Try this code :
it working fine in otp screen i am using four edit text in this activity follow these step
i am using TextWatcher class like this
/*Textwatcher class*/
public class GenericTextWatcher implements TextWatcher {
private View view;
public GenericTextWatcher(View view) {
this.view = view;
}
#Override
public void afterTextChanged(Editable editable) {
// TODO Auto-generated method stub
String text = editable.toString();
switch(view.getId()) {
case R.id.edit_otp1:
if(text.length()==1)
edit_otp2.requestFocus();
break;
case R.id.edit_otp2:
if(text.length()==1)
edit_otp3.requestFocus();
break;
case R.id.edit_otp3:
if(text.length()==1)
edit_otp4.requestFocus();
break;
case R.id.edit_otp4:
break;
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
}
Use textwatcher in edittext otp activity like this
/*call textwatcher class*/
edit_otp1.addTextChangedListener(new GenericTextWatcher(edit_otp1));
edit_otp2.addTextChangedListener(new GenericTextWatcher(edit_otp2));
edit_otp3.addTextChangedListener(new GenericTextWatcher(edit_otp3));
edit_otp4.addTextChangedListener(new GenericTextWatcher(edit_otp4));
it works for me please try.
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
}
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);
// ...
}
I want to set minimum and maximum input value for EditText box. I am creating one simple validation for EditText; it takes A-Z and 0-9 values with minimum 5 and maximum 8 character.
I set the maximum and other validations as follow:
<EditText
android:id="#+id/edittextKode_Listing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:layout_alignTop="#+id/textKode_listing"
android:layout_toRightOf="#+id/textKode_listing"
android:maxLength="8"
android:inputType="textCapCharacters"
android:digits="0,1,2,3,4,5,6,7,8,9,ABCDEFGHIJKLMNOPQRSTVUWXYZ"
/>
but not able to set minimum value requirement. My EditText box is in an alert dialog. I tried the following code to solve the problem:
private void openInboxDialog() {
LayoutInflater inflater = this.getLayoutInflater();
// declare dialog view
final View dialogView = inflater.inflate(R.layout.kirim_layout, null);
final EditText edittextKode = (EditText) dialogView.findViewById(R.id.edittextKode_Listing);
final EditText edittextalamat = (EditText) dialogView.findViewById(R.id.edittextAlamat);
edittextKode.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(edittextKode.getText().toString().length() > 0){
if(edittextKode.getText().toString().length() < 5)
{
edittextKode.setError("Error");
Toast.makeText(GPSActivity.this, "Kode listing value not be less than 5", Toast.LENGTH_SHORT).show();
edittextKode.requestFocus();
}
}
}
});
final AlertDialog.Builder builder = new AlertDialog.Builder(GPSActivity.this);
builder.setTitle("Kirim").setView(dialogView)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
gpsCoordinates = (TextView) findViewById(R.id.text_GPS_Coordinates);
kode = edittextKode.getText().toString();
alamat = edittextalamat.getText().toString();
catatan = edittextcatatan.getText().toString();
pengirim = edittextPengirim.getText().toString();
if (kode.length() > 0 && alamat.length() > 0
&& catatan.length() > 0 && pengirim.length() > 0) {
message = "Kode listing : " + kode + "\nAlamat : "
+ alamat + " \nCatatan : " + catatan + " \n Pengirim : " + pengirim
+ "\nKoordinat GPS : "
+ gpsCoordinates.getText().toString();
sendByGmail();
} else {
Toast.makeText(
getApplicationContext(),
"Please fill all three fields to send mail",
Toast.LENGTH_LONG).show();
}
}
});
builder.create();
builder.show();
}`
In this alert dialog, I have two EditText boxes. I want to apply my validation on first EditText. I called the setOnFocusChangeListener to check its minimum length on focus change. If the length is less than 5 then requested for focus, but it still types in second EditText box.
Could anyone please help me.
InputFilter[] lengthFilter = new InputFilter[1];
lengthFilter[0] = new InputFilter.LengthFilter(9); //Filter to 9 characters
mEditText.setFilters(lengthFilter);
This creates a filter to limit the number of characters.
There is no direct way to do this, the only way of doing it, as far as I know, is when the edit text loses focus or when the user submits the information you do length check and see if its less than 5 characters, e.g.
if (myTextBox.length() < 5)
{
Log.d("APP", "Sorry, you need to enter at least 5 characters";
}
else
{
Log.d("APP", "Input valid");
}
You can do something like this way....in this i checked the character length and if it is greater than 5 then the editText loses the focus..and After Touch on that it gets back the Focus..Try this ..i hope this will help you..
edittextKode.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
if(arg0.length()>5)
{
Toast.makeText(getApplicationContect(),"Max.value is 5",1).show();
edittextKode.setFocusable(false);
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
edittextKode.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
// TODO Auto-generated method stub
edittextKode.setFocusableInTouchMode(true);
return false;
}
});
You can try below code inside listener :
If condition is not met,
edittextKode.setFocus( true) ;
edittextKode.setFocusableInTouchMode( true) ;
edittextalamat.setFocus( false) ;
edittextalamat.setFocusableInTouchuha( false) ;
edittextKode.requestFocus();
I am able to call webservices now.
But In my project i want to populate the name of sponser corresponding to the sponser id .
For doing this I want to call a webservice on text changed listener of sponserid edittext or i have to monitor the focus changed of edittext.
Please guide me how to call webservice and populate another edittext.
Should i take keyevent ???
The codes i have tried so far are :
txtSpnID.setFocusable(true);
if(txtSpnID.isFocused()){
Log.v("TAG", "focus is on txtspid");
}else{
Log.v("TAG", "focus lost from txtspid");
}
This prints focus lost from txtspid on logcat.
if(txtSpnID.hasFocus()){
Log.v("TAG", "focus is on txtspid");
}else{
Log.v("TAG", "focus lost from txtspid");
}
this also prints the same
txtSpnID.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
Log.v("textfield","On text changed");
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
Log.v("textfield","before text changed");
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
Log.v("textfield text",txtSpnID.getText().toString());
Toast.makeText(Registration.this, "SponserID is"+txtSpnID.getText().toString(),
Toast.LENGTH_LONG);
if (txtSpnID.getText().length() == 0) {
Toast.makeText(Registration.this, "Enter SponserID ",
Toast.LENGTH_LONG);
} else {
String spnId = txtSpnID.getText().toString();
try {
//call webservice here and get response from the service
} catch (Exception e) {
}
}
}
});
this prints corresponding logs on logcat
but it does not show toast :(
please help me guys
you just made Toast ... but you did'nt show it ... use Toast.show() like this Toast.makeToast(.....).show();
.... remeber to call web service in different thread(to prevent ANR)