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();
Related
I have the following code
public class Answer extends Activity implements KeyListener{
EditText ed1;
Button b;
LinearLayout l;
int flag=0;
int f=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.answer);
ed1=(EditText)findViewById(R.id.answer);
b=(Button)findViewById(R.id.ans);
l=(LinearLayout)findViewById(R.id.An);
ed1.setKeyListener(this);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(flag==1)
l.setBackgroundColor(Color.BLACK);
}
});
}
public boolean onKeyUp(View arg0, Editable arg1, int arg2, KeyEvent arg3) {
// TODO Auto-generated method stub
switch(arg2){
case KeyEvent.KEYCODE_A:
if(f==0){
ed1.setText("");
f++;
flag=1;
}
}
return false;
}
The problem with this code is that on pressing 'a' it is setting color but after that it doesn't show anything in the edittext - ie it is setting color but after that it is not showing anything in edittext.If we press 'a' followed by 'n' then it will hide both 'a' and 'n' but i want to hide 'a' only
If you are looking to remove all of the a's from your EditText every time that you type 'a', then ed1.setText(""); is the culprit (it's clearing your EditText value every time).
Try this edit in your switch case:
String currText = ed1.getText().toString();
ed1.setText(currText.replace("a", ""));
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 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.
I've this problem of not being able to get the user input from the second inflated view.
I've upload an picture to this site http://postimage.org/image/b4syhdzrr/
as I'm still not allowed to post images directly on SO.
As you can see, the TextView only displays the top two EditText inputs + calculations, the third input however was not taken into consideration.(The first EditText for numbers is not inflated)
As I'm not sure how many EditText the end user would need.
How should I go about getting user inputs from all of the EditText ?
Here's what I had tried, setting up a SharePreferences to store the user input inside a TextWatcher, inside a OnClickListener, but with this code, the OnClickListener for the Plus button crashes the app even if the TextWatcher is empty.
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
ll = (LinearLayout) findViewById(R.id.llSetView);
ll.removeAllViews();
View person1 = View.inflate(BillCalculator1.this,R.layout.person1, null);
ll.addView(person1);
btP1Add = (Button) ll.findViewById(R.id.buttonP1Add);
btP1Gst = (Button) ll.findViewById(R.id.buttonP1GST);
btP1Add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
llNewRow = (LinearLayout) findViewById(R.id.llP1AddNewRow);
etNewRow = (EditText) findViewById(R.id.editTextNewRow);
View newRow = View.inflate(BillCalculator1.this,R.layout.newrow, null);
llNewRow.addView(newRow);
TextWatcher input = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
//SharedPreferences here
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
}
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
};
}
});
The XML for the inflated view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editTextNewRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:hint="Enter new amount">
<requestFocus />
</EditText>
Very new to programming and Android, do let me know if there's any additional information needed, Thank you very much.
I would try another approach to what you're trying to do. I would add a special TextWatcher to the inflated EditText and store the user entered values in an ArrayList. First of all you'll need two extra fields in your class:
private ArrayList<String> mData = new ArrayList<String>(); // this will store the entered values
private static int counter = 0; // to identify the rows
Make a class that implements the TextWatcher interface like this:
public class InputWatcher implements TextWatcher {
private int mRowNumber;
public InputWatcher(int rowNumber) {
mRowNumber = rowNumber;
}
#Override
public void afterTextChanged(Editable s) {
// here you'll add the text as the user enters it in the correct position in the
mData.set(mRowNumber, s.toString());
}
}
Then:
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
mData.clear();
counter = 0;
ll = (LinearLayout) findViewById(R.id.llSetView);
ll.removeAllViews();
// I sure hope that you have the Buttons with the id button1Add and buttonP1GST in the layout that you inflate
// otherwise the code will throw a NullPointerException when you use them below
View person1 = View.inflate(BillCalculator1.this,R.layout.person1, null);
ll.addView(person1);
btP1Add = (Button) ll.findViewById(R.id.buttonP1Add);
btP1Gst = (Button) ll.findViewById(R.id.buttonP1GST);
btP1Add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// add an entry in the data holder for this row
mData.add("");
View newRow = View.inflate(BillCalculator1.this,
R.layout.newrow, null);
EditText justAdded = (EditText) newRow
.findViewById(R.id.editTextNewRow);
justAdded.addTextChangedListener(new InputWatcher(counter));
ll.addView(newRow);
counter++;
}
});
When it's time to calculate the total, in a Button's OnClickListener, just do:
#Override
public void onClick(View v) {
int storedSize = mData.size();
int sum = 0;
for (int i = 0; i < storedSize; i++) {
sum += Integer.parseInt(mData.get(i).equals("") ? "0"
: mData.get(i));
}
Toast.makeText(getApplicationContext(), "Total" + sum, Toast.LENGTH_SHORT).show();
}
From your picture I didn't understand if you already start with one EditText in the layout(the one to the left of the + Button). If this is the case then you would have to manually set the InputWatcher to it and move the counter incrementation before adding the InputWatcher where you add the rows.
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)