gpt4 book ai didi

java - onAttach 中无法初始化接口(interface)对象?

转载 作者:行者123 更新时间:2023-12-02 04:58:50 25 4
gpt4 key购买 nike

我创建了一个接口(interface) DataPasserInterface 将数据从 fragment 传递到其托管 Activity 。我在 onAttach 中初始化了界面,如下代码所示,问题是,在运行时,应用程序崩溃,并且我收到下面发布的 logCat 错误。

我不知道为什么 this.dataPasserObj = (DataPasserInterface) Activity; 会导致错误? logcat 说,接口(interface)对象无法转换?!

界面:

private DataPasserInterface dataPasserObj;
...
...
...
public interface DataPasserInterface {

void onTopicsListChosen(ArrayList<String> chosenTopicsList);

}

onAttach:

@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.w(TAG, "@onAttach().");

this.dataPasserObj = (DataPasserInterface) activity;
this.designList = new ArrayList<ItemDesign>();
}

logcat:

 E/AndroidRuntime(7828): FATAL EXCEPTION: main
E/AndroidRuntime(7828): Process: com.example.mqtt_designlayout_02, PID: 7828
E/AndroidRuntime(7828): java.lang.ClassCastException: com.example.mqtt_designlayout_02.SettingsActivity cannot be cast to com.example.mqtt_designlayout_02.DataPasserInterface
E/AndroidRuntime(7828): at com.example.mqtt_designlayout_02.Eco_Settings_Frag.onAttach(Eco_Settings_Frag.java:95)

更新

托管 fragment 的 Activity 的 onCreate() 且该 Activity 实现该接口(interface)

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w(TAG, "@onCreate().");

this.mqttSettingsDB = new MQTT_Settings_DB(this);
this.sqliteDB = this.mqttSettingsDB.getWritableDatabase();

if (this.fragList == null) {
this.fragList = new ArrayList<Fragment>();

this.fragList.add(new MQTT_Settings_Frag());
this.fragList.add(new Eco_Settings_Frag());
this.fragList.add(new Logger_Settings_Frag());
}

initviews(R.layout.settings_activity);
setUpActionBar();
this.viewPager.setOnPageChangeListener(viewPagerListener);
}

最佳答案

ClassCastException: com.example.mqtt_designlayout_02.SettingsActivity

可能没有在 SettingsActivity 中实现 DataPasserInterface 接口(interface)

建议在Eco_Settings_Frag类中创建构造函数来获取DataPasserInterface接口(interface)并初始化其他值:

public Eco_Settings_Frag(Activity activity){
this.dataPasserObj = (DataPasserInterface) activity;
this.designList = new ArrayList<ItemDesign>();
}

并在创建Eco_Settings_Frag类的对象时传递SettingsActivity上下文:

 .....
this.fragList.add(new Eco_Settings_Frag(SettingsActivity.this));
this.fragList.add(new Logger_Settings_Frag());
.....

还在SettingsActivity Activity中实现DataPasserInterface接口(interface)

关于java - onAttach 中无法初始化接口(interface)对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28499311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com