android check edit text field - android

Ok, how can I setup edit checks for a text field to limit enter to certain characters and length.
Below is something I worked on but if the cursor is in the first position and i hit return it crashed
final EditText editText1 = (EditText)findViewById(R.id.editText9);
editText1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
editText1.setText("a");
editText1.setTag(1);
editText1.setId(idedittext1);
editText1.setBackgroundColor(0xff66ff66);
editText1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
//linear1.addView(editText1);
final String matchCharacters = "abcdefghijklmnopqrstuvwxyz.";
final CharSequence s_saved = "";
editText1.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count)
{
System.out.println("------------------------------------------------------------");
System.out.println("Entry: " + s + " " + s.length() + " " + start + " " + before + " " + count);
if (before == 1)
{
System.out.println("return");
}
if (s.length() > 4)
{
System.out.println("onTextChanged >4 replaced : " + s + " " + start + " " + before + " " + count);
String replaceStr = s.toString().substring(0, s.length() - 1);
editText1.setText(replaceStr);
editText1.setSelection(s.length() - 1);
}
if (s.length() > 0 && before != 1)
{
Integer sfound = 0;
String sstr = s.toString();
char[] sArray = sstr.toCharArray();
char[] mArray = matchCharacters.toCharArray();
System.out.println("sarray-marray " + " " + sstr + "-" + matchCharacters);
for (char sc : sArray) {
System.out.println("It worked1 " + sc);
for (char mc : mArray) {
System.out.println("It worked2 " + " " + sc + "-" + mc);
if (sc == mc) {
//System.out.println("It worked!");
sfound = sfound + 1;
} else {
//System.out.println("It did not work!");
}
}
}
System.out.println("slength-sfound " + " " + s.length() + "-" + sfound);
if (s.length() == sfound) {
System.out.println("MATCHED!");
} else {
System.out.println("NOMATCH!");
String replaceStr = s.toString().substring(0, s.length() - 1);
editText1.setText(replaceStr);
editText1.setSelection(s.length() - 1);
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Your can only enter the following characters: " + matchCharacters);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}
Any help is appreciated.
Thanks

To limit the EditText length
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="10"/>
To prevent certain character from being typed in
final EditText editText = (EditText) findViewById(R.id.edit_text);
final String matchCharacters = "aeiou";
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
String text = String.valueOf(editText.getText());
boolean edited = false;
for(int i=0; i<matchCharacters.length(); i++){
char toPrevent = matchCharacters.charAt(i);
if(text.indexOf(toPrevent) < 0){
continue;
}
text = text.replace(String.valueOf(toPrevent), "");
edited = true;
}
if(edited){
editText.setText(text);
}
}
});

Related

how to change the string display

how can i change string 980302 to string 98/03/02 in android studio
I have a variable of type string, for example 980302 I want to represent this way 98/03/02 in edittext Is
there a way?
Thanks for helping
This is probably the most trivial way of doing this...
String a = "980302";
String b = "" + a.charAt(0) + a.charAt(1) + "/" + a.charAt(2) + a.charAt(3) + "/" + a.charAt(4) + a.charAt(5);
YOUR_EDIT_TEXT.setText(b);
Or with a loop:
String a = "980302";
String b = "";
int i = 1;
while(i<a.length()){
if(i == 5){
b = b + a.charAt(i-1) + a.charAt(i);
}
else{
b = b + a.charAt(i-1) + a.charAt(i) + "/";
}
i = i + 2;
}
YOUR_EDIT_TEXT.setText(b);
If you're asking to show 980302 as 98/03/02 while typing, then the answer is using textchange event.
mMyEditText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
String str = s.toString();
if(str.length()==2 || str.length()==5){
str+= '/';
//Set str in edittext
}
}
);
a = a.substring(0, 1) + "/" + a.substring(2, 3) + "/" + a.substring(4, 5);

Math Quiz with true and false counters

I am implementing a scenario where user inputs an numeric answer in the edit text, which is being compared with addition of two numbers while inputting text using addTextChangeListener. I am trying to calculate true and false counters.
I get true counters perfectly in below code.
etTestAddAnswer.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) {
if (etTestAddAnswer.getText().toString().length() == (String.valueOf((firstDigit + secondDigit)).length())) {
if (etTestAddAnswer.getText().toString().equalsIgnoreCase("")) {
etTestAddAnswer.setError("Left Blank");
YoYo.with(Techniques.Wobble)
.duration(750)
.playOn(tlTestAddAnswer);
} else {
if (Integer.parseInt(etTestAddAnswer.getText().toString()) == (firstDigit + secondDigit)) {
correctCounter += 1;
etTestAddAnswer.setText("");
Toast.makeText(AdditionTestActivity.this, "Correct", Toast.LENGTH_SHORT).show();
if (finalCounter < 10) {
initGame();
} else {
testAddTime.cancel();
//Toast.makeText(AdditionTestActivity.this, "True Answer :" + correctCounter + "\n" + "Wrong Attempts" + falseCounter + "\n" + "Time " + toolbarTimeTestAddition.getText().toString(), Toast.LENGTH_SHORT).show();
}
} else {
YoYo.with(Techniques.RubberBand)
.duration(750)
.playOn(tlTestAddAnswer);
etTestAddAnswer.requestFocus();
falseCounter += 1;
Log.d(TAG, "False Answers: " + falseCounter);
etTestAddAnswer.setError("False Answer, \n Try Again..!!");
}
}
} else if (etTestAddAnswer.getText().toString().length() > (String.valueOf((firstDigit + secondDigit)).length())) {
YoYo.with(Techniques.RubberBand)
.duration(750)
.playOn(tlTestAddAnswer);
etTestAddAnswer.requestFocus();
Log.d(TAG, "onTextChanged: " + falseCounter);
//falseCounter++;
etTestAddAnswer.setError("False Answer, \n Try Again..!!");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
But the false counter is incorrect. Like if i am on fifth question and give my first wrong input, the false counters log is like this:
1
2
3
4
5
It should only increment one. Any ideas??

Android: NullPointerException in onTextChanged() method with EditText

Hello Android developer,
i keep getting a NullPointerException in my onTextChanged() method when EditText changes its text. BUT not on all smartphones. LG G2 does not throw any errors, but eg Samsung Galaxy S 4 does. I have two EditTexts. By entering numbers the program takes both values and calculates something. And really strange is that when the keyboard opens and i press any key and then DEL-key everything works.
here some code:
EditText bestellt = new EditText(this);
bestellt.setInputType(InputType.TYPE_CLASS_NUMBER);
bestellt.setGravity(Gravity.CENTER_HORIZONTAL);
bestellt.setEms(3);
bestellt.setTextAppearance(this, android.R.style.TextAppearance_Medium);
bestellt.setBackgroundColor(Color.parseColor("#DBF2FC"));
bestellt.setHint(Html.fromHtml("<small><small><small>" +
"Bestellt" + "</small></small></small>"));
//bestellt.setOverScrollMode(View.OVER_SCROLL_NEVER);
bestellt.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_FLAG_NAVIGATE_NEXT);
tempTableRow.addView(bestellt);
bestellt.setId(Integer.parseInt(Integer.toString(runde) + "90" + Integer.toString(i + 1) + "90" + Integer.toString(viewTeilID)));
//wieVieleReihen1 = tabellenLayout.getChildCount() - 1;
//scrollViewHor.setSmoothScrollingEnabled(false);
bestellt.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
viewEditText1 = v;
/*if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
//Toast.makeText(getBaseContext(), "Done gedrueckt", Toast.LENGTH_SHORT).show();
return true;
}*/
return false;
}
});
bestellt.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) {
//Toast.makeText(getBaseContext(), Integer.toString(v.getId()), Toast.LENGTH_LONG).show();
//int wieVieleReihen = tabellenLayout.getChildCount() - 1;
try{
int id1, id2, id3, tempPZ;
id1 = viewEditText1.getId();
String[] parts = Integer.toString(id1).split("90");
parts[2] = Integer.toString(Integer.parseInt(parts[2]) + 2);
id3 = Integer.parseInt(parts[0] + "90" + parts[1] + "90" + parts[2]);
parts[2] = Integer.toString(Integer.parseInt(parts[2]) - 1);
id2 = Integer.parseInt(parts[0] + "90" + parts[1] + "90" + parts[2]);
//kontrolle.setText("ID1: " + id1 + " ID2: " + id2 + " ID3: " + id3);
//viewEditText1.requestFocus();
/*INSIDE HERE SHOULD NOT BE A MISTAKE
try {//es müssen unbedingt werte eingegeben worden sein
if (false) {
//((EditText) findViewById(id1)).getText().toString().equals("") || ((EditText) findViewById(id1)).getText().toString().trim().length() == 0 || (((EditText) findViewById(id2)).getText().toString().equals("")) || ((EditText) findViewById(id2)).getText().toString().trim().length() == 0
//Toast.makeText(getBaseContext(), "Werte eingeben und bestaetigen!", Toast.LENGTH_SHORT).show();
} else
tempPZ = 0; //keine Ahnung warum
//((EditText) findViewById(id1)).;
tempPZ = berechnePunktzahl(Integer.parseInt(((EditText) findViewById(id1)).getText().toString()), Integer.parseInt(((EditText) findViewById(id2)).getText().toString()));
((TextView) findViewById(id3)).setText(Integer.toString(tempPZ));
int c;
int summe = 0;
int tempoID = 0;
for (c = 0; c < runde; c++) {
tempoID = Integer.parseInt((c + 1) + "90" + parts[1] + "90" + "3");
summe = summe + Integer.parseInt(((TextView) findViewById(tempoID)).getText().toString());
}
((TextView) findViewById(Integer.parseInt("222" + parts[1]))).setText(Integer.toString(summe));
//punktZahlen.add(Integer.parseInt(parts[0])-1,tempPZ);
//Integer sum = 0;
//for ( Integer i : punktZahlen ) {
// sum += i;
//}
//((TextView) findViewById(Integer.parseInt("222"+parts[1]))).setText(Integer.toString(sum));
} catch (Exception e) {
//Toast.makeText(getBaseContext(), "Werte eingeben!", Toast.LENGTH_LONG).show();
}
*/ INSIDE HERE SHOULD NOT BE A MISTAKE
} catch(Exception e){ //this throws NullPointerException
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
This is the error Stacktrace:
07-17 12:41:05.250 32282-32282/com.martins.martin.bestellen E/YOUR_APP_LOG_TAG﹕ I got an error
java.lang.NullPointerException
at com.martins.martin.bestellen.SecondActivity$2.onTextChanged(SecondActivity.java:278)
at android.widget.TextView.sendOnTextChanged(TextView.java:8910)
at android.widget.TextView.setText(TextView.java:4866)
at android.widget.TextView.setText(TextView.java:4716)
at android.widget.EditText.setText(EditText.java:109)
at android.widget.TextView.setText(TextView.java:4691)
at android.widget.TextView.onRestoreInstanceState(TextView.java:4583)
at android.view.View.dispatchRestoreInstanceState(View.java:13722)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2849)
at android.view.View.restoreHierarchyState(View.java:13700)
at com.android.internal.policy.impl.PhoneWindow.restoreHierarchyState(PhoneWindow.java:1952)
at android.app.Activity.onRestoreInstanceState(Activity.java:983)
at android.app.Activity.performRestoreInstanceState(Activity.java:955)
at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1144)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$1000(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5476)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
I hope you will find the problem. Should have to do something with the Keyboard (any Buffer????)
Thanks a lot,
Martin
Now I solved it by simulting a DEL-Keypress programmatically. Its a very bad solution but i could not find the problem...

PhoneUtils equivalent code for edit text

Do you have a piece of code to manually format a given phone number in Android? I don't want use PhoneUtils. I need this for a project for my course.
I had a similar issue, please check my code below:
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
String str;
/*Log.i("ED",
"LengthBefore before (lengthBefore = lengthAfter;): "
+ String.valueOf(lengthBefore));*/
lengthBefore = lengthAfter;
lengthAfter = s.length();
/*Log.i("ED",
"LengthBefore after (lengthBefore = lengthAfter;): "
+ String.valueOf(lengthBefore));*/
if ((lengthBefore < lengthAfter) || lengthBefore == 0)
{
if (!isResetClicked)
{
if (s.length() == 0)
{
editPhoneNumber.setText("(");
}
if (s.length() == 1)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText("(" + str);
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 4)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + ") ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 9)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
if (s.length() == 12)
{
str = editPhoneNumber.getText().toString();
editPhoneNumber.setText(str + " ");
editPhoneNumber.setSelection(editPhoneNumber
.getText().length());
}
}
}
lengthAfter = s.length();
/*Log.i("ED", "LengthAfter after (lengthAfter = s.length();): "
+ String.valueOf(lengthAfter));
Log.i("ED", "LengthBefore: " + String.valueOf(lengthBefore));
Log.i("ED", "LengthAfter: " + String.valueOf(lengthAfter));*/
}

Convert drawable to a specific string

I have a chat app which I want to extend with emoticons.
This code is used to insert a smilie in the text:
Spanned cs = Html.fromHtml("<img src ='"+ index +"'/>", imageGetter, null);
int cursorPosition = content.getSelectionStart();
content.getText().insert(cursorPosition, cs);
This is working great. The smilies show up in the textView at the right place.
Now I want to send the text to my server via HTTP.
I would like to store ":)" instead of the image as for ones using an older app version the image can not be displayed. In the new version I convert ":)" to the image before displaying the text. Is there any way to convert the image to a specific string?
if you want to replace your emoticons try this:
EditText et = new EditText(this);
et.setTextSize(24);
et.setHint("this view shows \":)\" as an emoticon, try to type \":)\" somewhere");
final Bitmap smile = BitmapFactory.decodeResource(getResources(), R.drawable.emo_im_happy);
final Pattern pattern = Pattern.compile(":\\)");
TextWatcher watcher = new TextWatcher() {
boolean fastReplace = true;
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Log.d(TAG, "onTextChanged " + start + " " + before + " " + count);
if (fastReplace) {
if (start > 0 && count > 0) {
String sub = s.subSequence(start - 1, start + 1).toString();
if (sub.equals(":)")) {
Spannable spannable = (Spannable) s;
ImageSpan smileSpan = new ImageSpan(smile);
spannable.setSpan(smileSpan, start-1, start+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
} else {
Spannable spannable = (Spannable) s;
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int mstart = matcher.start();
int mend = matcher.end();
ImageSpan[] spans = spannable.getSpans(mstart, mend, ImageSpan.class);
Log.d(TAG, "onTextChanged " + mstart + " " + mend + " " + spans.length);
if (spans.length == 0) {
ImageSpan smileSpan = new ImageSpan(smile);
spannable.setSpan(smileSpan, mstart, mend, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
Log.d(TAG, "onTextChanged " + s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
Log.d(TAG, "afterTextChanged " + s);
}
};
et.addTextChangedListener(watcher );
setContentView(et);
here if fastReplace == true you don't have to scan the whole text but it's only minimal implementation: works only if you type ")" right after typed ":", if fastReplace == false it replaces every occurrence of ":)" with a smiley but it has to scan the whole text so it's a bit slower when text is quite large

Categories

Resources