【问题标题】:Null object reference while trying to pass array list using interface尝试使用接口传递数组列表时为空对象引用
【发布时间】:2017-12-19 08:03:23
【问题描述】:

您好,我正在尝试将我的活动中的数组列表传递给片段,这就是我所做的:

第一个活动:

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;
}

片段

 OnActivityCreated
((FirstActivity) getActivity()).setInterface(this);

 @Override
public void onDataRecieved(ArrayList<Result> response) {
    processData(response);
}

例外

Attempt to invoke interface method 'void **************.onDataRecieved(java.util.ArrayList)' on a null object reference

我的想法:

我打这个电话

instanceForInterface.onDataRecieved(results); in OnCreate()

在初始化之前

((FirstActivity) getActivity()).setInterface(this); in OnActivityCreated()

请解决??

谢谢

【问题讨论】:

标签: android interface


【解决方案1】:

问题是您的片段的onActivityCreated() 方法是在您的活动的onCreate() 方法之后调用的。

为了实现您想要的行为,您可以做的最小更改是在您的活动中使用onResumeFragments() 方法。也就是说,从您的onCreate 中删除instanceForInterface.onDataRecieved(results); 行并添加以下代码:

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    instanceForInterface.onDataRecieved(results);
}

onResumeFragments() 将在您的活动的onCreate() 和您的片段的onActivityCreated() 方法之后被系统调用。

话虽如此,您很有可能采用完全不同的方法会更好。例如,您可以让您的活动为results 公开一个getter,并让您的片段检索要使用的结果(而不是让您的活动存储对片段的引用)。

进一步了解 Activity 和 Fragment 生命周期: https://developer.android.com/guide/components/activities/activity-lifecycle.html https://developer.android.com/guide/components/fragments.html

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2021-08-13
    • 2013-04-22
    • 1970-01-01
    • 2020-09-29
    • 2019-03-02
    • 2021-06-12
    • 2018-11-20
    • 2019-06-26
    相关资源
    最近更新 更多