我在Android应用程序上实现java界面时遇到问题... 调用事件时应用程序崩溃。具体来说,在线“listener.callBack(String.valueOf(stringListValue.get(position)));” 这是Logcat:
03-29 15:23:38.659 12568-12568/com.robertot.timereport E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.robertot.timereport, PID: 12568
java.lang.NullPointerException
at com.robertot.timereport.com.robertot.timereport.pages.MainActivity$2.onItemSelected(MainActivity.java:231)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:893)
at android.widget.AdapterView.access$200(AdapterView.java:48)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:861)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5081)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
这是MainActivity:
public class MainActivity extends FragmentActivity
{
//[...]
private OnSelectItemSpinner listener;
public interface OnSelectItemSpinner
{
public void callBack(String idjob);
}
@Override
protected void onCreate(Bundle savedInstanceState) { //[...]
}
//[...]
ArrayAdapter<String> spnAdapt = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, stringListName);
spnAdapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnJobList.setAdapter(spnAdapt);
spnJobList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{
switch (FragmentTag)
{
//Summary - Refresh ListView
case 0:
//CRASH HERE...
listener.callBack(String.valueOf(stringListValue.get(position)));
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0){}
});
//[...]
当我调用界面时,这是片段:
public class SummaryFragment extends Fragment implements MainActivity.OnSelectItemSpinner
{
@Override
public void callBack(String idjob)
{
//do work
}
}
当我错的时候?
谢谢!!!
答案 0 :(得分:0)
您收到NullPointerException
因为您未在任何地方初始化listener
。
OnSelectItemSpinner listener = new OnSelectItemSpinner()
{
@Override
public void callBack(String idjob)
{
// Do smth
}
};
答案 1 :(得分:0)
如果您想在活动和片段之间进行通信,您必须注意以下提示: 要允许片段与活动进行通信,您可以在片段类中定义界面并实施它在活动中。 Fragment在其 onAttach()生命周期方法中捕获接口实现,然后可以调用Interface方法以与Activity通信。
请参阅Communicating Between Activity and Fragment
如果您想要反向沟通,可以执行以下代码:
public class MainFragment extends Fragment {
public void callBack() {
// Do SomeThing
}
}
public class MainActivity extends Activity {
public void callFragmentCallBack() {
MainFragment fragment = (MainFragment) getFragmentManager().findFragmentById(R.id.fragment_main);
fragment.callBack(); // This line is important
}
}