4

I want to limit the text length of edit text ui element via code:

EditText et = (EditText) parent.findViewById(R.id.smsBody);;
int maxLength = 300;

InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
et.setFilters(FilterArray);

But this gives me a null pointer exception in the last line. Any ideas whats wrong? This codes is in the onPostExecute method of my async task class. Parent is the main activity.

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
  • 1
    Check whether the et variable is not null. If it is null then it was not found in the parent layout. – Flo Dec 29 '11 at 15:23
  • but that makes no sence because its actually there^^ – DarkLeafyGreen Dec 29 '11 at 15:28
  • I would bet that @Flo is right, et is probably coming back null from findViewById(). Post some more of your code(Specifically anything related to the parent reference) and if possible explain the context of your layouts (i.e. are we inside the main layout of an activity? In a dialog within an activity? etc) Try using YourActivity.findViewById(), instead of parent.findViewById() – FoamyGuy Dec 29 '11 at 15:28
  • oh I just realized that parent is wrong, its not the main layout but another layout, how can I access it? – DarkLeafyGreen Dec 29 '11 at 15:36
  • ComposeActivity.findViewById(R.id.smsBody); seems to be wrong – DarkLeafyGreen Dec 29 '11 at 15:41
  • findViewById() is not a static method so you can't call it like that. You need an instance of it or call it within the Activity itself. – Flo Dec 29 '11 at 15:59
  • possible duplicate of [Limit text length of EditText in Android](http://stackoverflow.com/questions/3285412/limit-text-length-of-edittext-in-android) – Ratul Sharker Feb 04 '15 at 07:16

1 Answers1

4

You should be able to put in your .xml file under your edit text:

android:maxLength="300"

You dont need any of that other stuff in your .java file. Your .xml file controls things like color, length, size, etc.

Paul Maserrat
  • 3,411
  • 3
  • 22
  • 24
  • Also you dont need "parent" when finding your editText. that might be what is causing your null pointer. instead of: EditText et = (EditText) parent.findViewById(R.id.smsBody); Use: EditText et = (EditText) findViewById(R.id.smsBody); This is how i have done it in all my android project. – Paul Maserrat Dec 29 '11 at 15:56