0
我想從選擇的名稱從ListView傳遞給MainActivity從片段,但我在onItemClick方法中獲取空指針異常。 下面是從片段代碼:將listview選中的項從片段傳遞到活動
getListText getListTextObject;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView=inflater.inflate(R.layout.fragment_main, container, false);
listView=(ListView) rootView.findViewById(R.id.profile_list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
nameListItem=(TextView) view;
String text=nameListItem.getText().toString();
getListTextObject.getData(text);
}
});
return rootView;
}
public void onAttach(Context context){
super.onAttach(context);
try{
getListTextObject=(getListText) context;
}catch (ClassCastException e){
throw new ClassCastException(context.toString() + " must implement getListText");
}
}
public interface getListText{
public void getData(String s);
}
堆棧跟蹤的空指針異常:
02-25 10:17:14.445 7388-7388/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.user.example.FragmentMain$1.onItemClick(FragmentMain.java:67)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2855)
at android.widget.AbsListView$1.run(AbsListView.java:3529)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
請發佈一些NPE的堆棧跟蹤。 –
添加了一些堆棧跟蹤 –
在此處發佈完整代碼 –