使用自定义事件监听器java

时间:2016-02-26 16:51:23

标签: java android

我正在尝试从我的MainActivity设置一个自定义事件监听器到另一个单例类,我似乎无法弄清楚我做错了什么。我在mainactivity中设置了一个映射片段,当调用onLocationChanged()时,我希望我的DB类侦听这个新位置以将其添加到我的数据库中。这就是我到目前为止所拥有的。我只显示与接口和监听器相关的代码:

MainActivity.java

public List<OnNewLocationRaisedListener> locationListeners;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    ...
    locationListeners = new ArrayList<OnNewLocationRaisedListener>();
    ...
}

@Override
public void onLocationChanged(Location location) {
    WeatherDBAccess._context = this;
    m_CurrentLocation = location;
    WeatherEvent event = new WeatherEvent();

    if (record) {
        LatLng currLatLng = new LatLng(m_CurrentLocation.getLatitude(), m_CurrentLocation.getLongitude());
        for(OnNewLocationRaisedListener listener: locationListeners){
            listener.OnNewLocationRaised(event,currLatLng);
        }

    }
}

public interface OnNewLocationRaisedListener {
    void OnNewLocationRaised(WeatherEvent event, LatLng latlon);
}

在My WeatherDBAccess.java类中我尝试设置它以便我可以将其上下文添加到mNewLocationListeners列表,但它不允许我这样做,我得到一个'非静态字段不能从静态上下文引用'错误,我不知道如何解决它:

WeatherDBAccess.java:

public class WeatherDBAccess extends SQLiteAssetHelper
            implements MainActivity.OnNewLocationRaisedListener {
    public static WeatherDBAccess Instance() {
        if(_context == null)
            throw new NullPointerException("You must supply the WeatherDBAccess._context prior to calling Instance()");

        if(_instance == null)
            _instance = new WeatherDBAccess(_context);

        return _instance;
    }

    public WeatherDBAccess(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        db = this.getWritableDatabase();
        Log.d("WeatherDBAccess", "Instance Created " + db.getPath());

        MainActivity.locationListeners.add(this); //error

    }

    @Override
    public synchronized void OnNewLocationRaised(WeatherEvent event, LatLng latlon ) {
        addTravelData(event); //this method puts the event & latlon into my database

    }
}

我可以不从活动中做到这一点吗?

1 个答案:

答案 0 :(得分:2)

MainActivity.locationListeners是一个实例成员,无法像您当前在WeatherDbAccess中尝试的那样静态访问。

您应该做什么,因为WeatherDBAccess是一个单身人士,请注册并从locationListener内注销MainActivity。它应该在您注册和取消注册LocationListener的相同生命周期回调方法中。

由于您没有显示代码可以假设它位于onResume()onPause()中,但您可以将添加和删除方法放在它们真正属于的任何位置。

@Override
public void onResume() {
    super.onResume();
    locationListeners.add(WeatherDBAccess.Instance());
}

@Override
public void onPause() {
    super.onPause();
    locationListeners.remove(WeatherDBAccess.Instance());
}