AutoCompleteTextView NullPointer Exception
I have searched a long time and cannot find a solution to my problem. I am trying to create a Dialog with an AutoCompleteTextView. I followed the tutorial on the Android developer website, and it worked great. I have been successful using layouts on Dialogs before, so I thought this would be just as easy. I created a layout for my Dialog and I made sure that the AutoCompleteTextView has an ID. Here's where the interesting stuff happens...
dialog.setContentView(R.layout.auto_layout);
AutoCompleteTextView auto_tv = (AutoCompleteTextView)findViewById(R.id.role_ac);
Here is the layout as well.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Role" />
<AutoCompleteTextView android:id="@+id/role_ac" android:layout_width="280dip" android:layout_height="wrap_content"/>
<Button android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="Done"
android:id="@+id/auto_doneButton" />
</LinearLayout>
For some reason, auto_tv is null even though it does exist in the layout auto_layout. The only way I have been able to get an AutoCompleteTextView in a Dialog is by building the layo开发者_如何学Pythonut programmatically. Why is the AutoCompletTextView null when I try to use it? Did I forget something in my layout or am I not constructing the object correctly? Any help on this would be greatly appreciated. Thanks.
You're mixing two different contexts in your calls to setContentView
and findViewById
. In the first statement you're setting the content view of the object dialog
. In the second statement you're looking for an view in the parent activity. You want to make both calls using the dialog object. The correct syntax should be:
dialog.setContentView(R.layout.auto_layout);
AutoCompleteTextView auto_tv = (AutoCompleteTextView) dialog.findViewById(R.id.role_ac);
Ok. Just figured it out. Looked at too much code to catch my mistake. Here's the solution.
dialog.setContentView(R.layout.auto_layout);
AutoCompleteTextView auto_tv = (AutoCompleteTextView)dialog.findViewById(R.id.role_ac);
I needed to specify to use the Dialog's layout and not the main application's layout that was implied by not using dialog.findViewByID.
精彩评论