Observed / Observer not working?

I tried to implement a static Observable in my Application subclass, but it does not work. No exceptions or error messages, but my callback update () was not called.

Myapplication.java

public class MyApplication extends Application{
    public static Observable appObserver = new Observable();

    public void onCreate(){
        super.onCreate();        
    }

}

Foo.java

MyApplication.appObserver.notifyObservers( "Hello world" );

Barfragment.java

public class BarFragment extends Fragment implements Observer{

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);                
        MyApplication.appObserver.addObserver(this);
    }


    @Override
    public void onDestroy() {       
        MyApplication.appObserver.deleteObserver(this);
        super.onDestroy();
    }


    @Override
    public void update(Observable observable, Object data) {
        Log.i("BarFragment", data.toString()); // Should log, but doesn't
    }

}

What else, I tried to record a simple native Observable, and then everything worked like a charm, just replacing it public static Observable appObserver = new Observable();withpublic static MyObservable appObserver = new MyObservable();

MyObservable.java

public class MyObservable {
    protected List<Object> observers = new ArrayList<Object>();

    public void addObserver(Object observer){
        observers.add(observer);
    }

    public void notifyObservers(Object data){
        for( int i=0; i<observers.size(); i++ ){
            ((Observer) observers.get(i)).update(null, data);
        }
    }
}

What am I missing?

I am testing this on a Nexus One with Android 2.3.6, if that matters.

+4
source share
2 answers

, Observer, -, setChanged() notifyObservers(). , setChanged() , , Observable.

, , , , ...

public class MyObservable extends Observable{

    @Override
    public boolean hasChanged() {
        return true; //super.hasChanged();
    }

}
+9

BadCash , - Observable. , , Java 8. , hasChanged(), notifyObservers(), :

class WorkingObservable extends Observable{
    @Override
    public void notifyObservers(){
        setChanged();
        super.notifyObservers();
    }
};

. , , Observable hasChanged() , , . changed. , .

+1

All Articles