Android 尝试使用接口传递数组列表时的空对象引用
您好,我正在尝试将一个数组列表从我的活动传递到片段,这就是我所做的: 第一项活动:Android 尝试使用接口传递数组列表时的空对象引用,android,interface,Android,Interface,您好,我正在尝试将一个数组列表从我的活动传递到片段,这就是我所做的: 第一项活动: AdminInterface instanceForInterface; OnCreate // System.out.println(results.size) ; //works fine instanceForInterface.onDataRecieved(results); // here I am getting the exception // public interface AdminIn
AdminInterface instanceForInterface;
OnCreate
//
System.out.println(results.size) ; //works fine
instanceForInterface.onDataRecieved(results); // here I am getting the exception
//
public interface AdminInterface {
void onDataRecieved(ArrayList <Result> response);
}
public void setInterface(UserFragment anInterface) {
this.instanceForInterface = anInterface;
}
我的想法是:
我打这个电话
instancePrinterface.ondataReceived(结果)代码>在OnCreate()中
在
((FirstActivity)getActivity()).setInterface(this)代码>在OnActivityCreated()中
解决方案请
谢谢问题在于,在活动的onCreate()
方法之后,会调用片段的onActivityCreated()
方法
为实现所需的行为,您可以做的最小更改是在活动中使用onResumeFragments()
方法。也就是说,删除行instancePrinterface.onDataReceived(结果)从您的onCreate
中选择code>,然后添加此代码:
@Override
protected void onResumeFragments() {
super.onResumeFragments();
instanceForInterface.onDataRecieved(results);
}
在活动的onCreate()
和片段的onActivityCreated()
方法之后,系统将调用onResumeFragments()
也就是说,如果采用完全不同的方法,你的境况会更好。例如,您可以让活动为结果
公开一个getter,并让片段检索要处理的结果(而不是让活动存储对片段的引用)
进一步阅读活动和片段生命周期:
可能重复的put-inonAttach
而不是创建的OnActivity
最好传递ArrayList
,因为Bundle
InstancePrinterface
为空。您应该使用debug来检查其原因。
Attempt to invoke interface method 'void **************.onDataRecieved(java.util.ArrayList)' on a null object reference
@Override
protected void onResumeFragments() {
super.onResumeFragments();
instanceForInterface.onDataRecieved(results);
}