0
final String[] defaulttask1  = {"abc"," def"," ghi"};
final AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView)this.findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,defaulttask1);
autoCompleteTextView.setThreshold(0);
autoCompleteTextView.setAdapter(adapter);

I have a method using autoCompleteTextView.getText().toString().While the user types words which is not in the array, it may happen "null pointer exception"

Is there any solution that I can use autoCompleteTextView, that can search for user and let user enter text they want?

P.S. sorry, I'm not a native speaker, there might be some grammar mistake.

Lal
  • 14,726
  • 4
  • 45
  • 70
ian1228
  • 1
  • 1
  • `AutoCompleteTextView` is an `EditText` so the user can type anything `EditText` accepts – pskink Aug 16 '15 at 17:36
  • If you want the user to enter anything that they want, then why do you use AutoCompleteTextView? Use EditText Instead.. – Lal Aug 16 '15 at 17:36

1 Answers1

1

AutoCompleteTextView is right solution for your needs

An editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.

AutoCompleteTextView will allow user to type whatever he/she want but will give suggestions from array.

autoCompleteTextView.getText().toString()

will not return null in case of user types words which is not in the array. It will return whatever text is there right now in text view. It might crash if you do getText().toString() on a empty text view. So have a check before you convert textview to string

if(autoCompleteTextView.getText()!=null)
String textviewString = autoCompleteTextView.getText().toString()
Hari Ram
  • 3,098
  • 5
  • 23
  • 30
  • http://stackoverflow.com/questions/16178481/android-prorgram-crashes-when-i-attempt-to-gettext-from-an-autocompletetext I saw this, and I think it is might be the solution. I haven't try, and my question is that in my code I use onCreat, is there any different I put the code in onCreate() and onCreateView()? – ian1228 Aug 17 '15 at 05:37
  • Yes there is difference, in oncreate you can simply do setContentView() but in onCreateView() you will have to inflate view like this public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.your_layout, container, false); and then do view.findViewByID whenever you want to get something by id. – Hari Ram Aug 17 '15 at 06:10