【问题标题】:ArrayList items unreachable after sending through the interface通过接口发送后无法访问的 ArrayList 项
【发布时间】:2013-09-19 13:56:18
【问题描述】:

问题是我无法从ArrayList<Integer> 中检索Integer 值,该值是从TimePickerFragment 通过接口发送到FragmentActivity。当我尝试获取保存的值时(请参阅下面的 FragmentActivity),我得到“不兼容的类型。必需:java.lang.Integer,找到:java.lang.Object”。

时间选择器片段:

public class TimePickerFragment extends DialogFragment
    implements TimePickerDialog.OnTimeSetListener {

Listener mListener;

// declaration of the interface
public interface Listener {
    public void onUserTimeChoice(ArrayList dataSet);
}


// registration of the listener
public void registerListener(Listener listener) {
    mListener = listener;
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current time as the default values for the picker
    final Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    // Create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute,
            DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    // Do something with the time chosen by the user
    ArrayList<Integer> mAList = new ArrayList();

    mAList.add(hourOfDay);
    mAList.add(minute);
    mListener.onUserTimeChoice(mAList);
}
}

FragmentActivity(摘录):

@Override
public void onUserTimeChoice(ArrayList dataSet) {

    Integer hour = dataSet.get(0);   //  <--- incompatible types
    Integer minute = dataSet.get(1); // <--- incompatible types

}

【问题讨论】:

  • 您是否尝试将接口方法更改为 public void onUserTimeChoice(ArrayList dataSet){...?

标签: java android interface android-fragments


【解决方案1】:

dataSet 中使用泛型类型而不是raw typeArrayList dataSet 等价于ArrayList&lt;Object&gt; dataSet

使用List而不是ArrayList向接口添加代码

public void onUserTimeChoice(List<Integer> dataSet) {

【讨论】:

  • 当我们这样做时,您应该使用List&lt;Integer&gt;,最好更通用并针对接口进行编码(List 是一个接口)。还是您明确希望调用者传递ArrayList
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 2015-01-26
  • 2015-08-17
  • 2020-09-11
  • 2018-12-27
  • 1970-01-01
相关资源
最近更新 更多