接口对象无法在onAttach中初始化?

时间:2015-02-13 12:09:09

标签: java android interface

我创建了一个接口DataPasserInterface,用于将数据从片段传递到其托管活动。我在onAttach中启用了界面,如下面的代码所示,问题是,在运行时,应用程序崩溃,我收到以下发布的logCat错误。

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

接口

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)

更新

承载片段的活动的onCreate(),此活动实现界面

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

1 个答案:

答案 0 :(得分:2)

  

ClassCastException:com.example.mqtt_designlayout_02.SettingsActivity

可能未在DataPasserInterface

中实施SettingsActivity界面

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

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

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

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

DataPasserInterface活动

中实施SettingsActivity界面