Android: NullPointerException in onTextChanged() method with EditText - android

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...

Related

android check edit text field

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);
}
}
});

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??

Using keyListener and textChangedListener together in Android editText

I am trying to use both
editPhoneNumber.setKeyListener(new KeyListener()
and
editPhoneNumber.addTextChangedListener(new TextWatcher()
together but it seems that they block eachother, my editText is no longer editable.
Thanks for any help
Edit:
I am trying to format the input as the user types:
Input:5551112233
Formatted Input: (555) 111 22 33
The formatting part works well but the reason I am trying to add the KeyListener is when the user tries to delete (by pressing on delete key) and when the inputs length becomes -let's say- 12 characters TextChangedListener interrupts the user to delete by always putting a " " at he end of the text. That is why I am trying to disable the TextChangedListener when the input is a delete key.
boolean isResetClicked;
EditText editPhoneNumber;
Button buttonReset;
protected void onCreate(Bundle savedInstanceState)
{
editPhoneNumber = (EditText) findViewById(R.id.editPhoneNumber);
buttonReset = (Button) findViewById(R.id.buttonResetPhoneNumber);
buttonReset.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
isResetClicked = true;
editPhoneNumber.getText().clear();
isResetClicked = false;
}
});
editPhoneNumber.setKeyListener(new KeyListener()
{
#Override
public boolean onKeyUp(View view, Editable text, int keyCode,
KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DEL)
{
isResetClicked = true;
}
else
isResetClicked=false;
return false;
}
#Override
public boolean onKeyOther(View view, Editable text, KeyEvent event)
{
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onKeyDown(View view, Editable text, int keyCode,
KeyEvent event)
{
return false;
}
#Override
public int getInputType()
{
// TODO Auto-generated method stub
return 0;
}
#Override
public void clearMetaKeyState(View view, Editable content,
int states)
{
// TODO Auto-generated method stub
}
});
editPhoneNumber.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
String str;
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());
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s)
{
}
});
Edit 2:
Even if I'm still unable to understand why two event listeners block my edittext, I solved my problem by modifying the code:
#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));*/
}
As when the user tries to delete a character the new length will be shorter than the older one. So I prevented the code from checking the length by:
if ((lengthBefore < lengthAfter) || lengthBefore == 0)

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));*/
}

How to format person height in EditText to reflect inches and feet?

I have an EditText field in my app which is for person's height. How do I format it to make it look like say 5'9"? When a person types 5 the app should add ' by itself and when a person types 9 it should add ". How do I do that? Thank you.
Use this:
public class TextWatcherActivity extends Activity {
EditText e;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e = (EditText) findViewById(R.id.editText1);
e.addTextChangedListener(new CustomTextWatcher(e));
}
}
class CustomTextWatcher implements TextWatcher {
private EditText mEditText;
public CustomTextWatcher(EditText e) {
mEditText = e;
}
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) {
int count = s.length();
String str = s.toString();
if (count == 1) {
str = str + "'";
} else if (count == 2) {
return;
} else if (count == 3) {
str = str + "\"";
} else if (count >= 4) {
return;
}
mEditText.setText(str);
mEditText.setSelection(mEditText.getText().length());
}
}
Edit:
If user can insert one,two and more digit between ' and " change afterTextChanged in above code like this:
public void afterTextChanged(Editable s) {
int count = s.length();
String str = s.toString();
if (count == 1) {
str = str + "'";
} else if (count == 3) {
str = str + "\"";
} else if ((count > 4) && (str.charAt(str.length() - 1) != '\"') ){
str = str.substring(0, str.length() - 2) + str.charAt(str.length() - 1)
+ "\"";
} else {
return;
}
mEditText.setText(str);
mEditText.setSelection(mEditText.getText().length());
}
use this :
for delete "'".
mBinding.edtHeight.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
if (mBinding.edtHeight.getText().length() == 2) {
mBinding.edtHeight.setText("");
}
}
return false;
}
});

Categories

Resources