当我尝试在按下片段中的按钮时从AutoCompleteTextView中提取文本时,抛出NullPointerException。这是我的代码......
public class TreeMenuFragment extends SherlockFragment{
protected View view;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.treemenu, container, false);
//Auto-Complete
AutoCompleteTextView autoView = (AutoCompleteTextView) view.findViewById(R.id.edit_message);
String[] itemOptions = getResources().getStringArray(R.array.edit_message);
ArrayAdapter<String> theAdapter =
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, itemOptions);
autoView.setAdapter(theAdapter);
((BaseAdapter) autoView.getAdapter()).notifyDataSetChanged();
((ViewGroup) autoView.getParent()).removeView(autoView);
container.addView(autoView);
Button b = (Button) view.findViewById(R.id.post_blacklist_button);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AutoCompleteTextView editText=(AutoCompleteTextView) view.findViewById(R.id.edit_message);
String blackListItem = editText.getText().toString();
editText.setText("");
MainActivity.getInstance().postBlackListItem(blackListItem);
}
});
return view;
}
}
相关的xml在这里:
<AutoCompleteTextView
android:id="@+id/edit_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/my_hint" />
<Button
android:id="@+id/post_blacklist_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/update_button" />
* 更新: *当我尝试将自动完成文档转换从v更改为View时,我的日志会打印以下内容:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.privacyapp.TreeMenuFragment$1.onClick(TreeMenuFragment.java:34)
at android.view.View.performClick(View.java:2532)
at android.view.View$PerformClick.run(View.java:9293)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:4263)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
更改
AutoCompleteTextView editText=(AutoCompleteTextView) v.findViewById(R.id.edit_message);
到
AutoCompleteTextView editText=(AutoCompleteTextView) view.findViewById(R.id.edit_message);
此处v
是您点击的Button
,我假设view
是膨胀的xml,您可以在其中找到AutoCompleteTextView
。这意味着,当您尝试在其上调用函数时,editText
为null
并抛出NPE
editText.getText().toString();
如果这不能解决问题,那么请发布logcat,但仍然需要更改此行
将autoView
声明为成员变量,然后您只需初始化一次。然后在AutoCompleteTextView
内使用onClick
的该实例获取文字