Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable/Observer Android

Tags:

java

android

EDIT please see Observer Observables implementing issue - It seems I was overriding methods that didn't need to be and not calling setChanged(); before notify();

I've been reading up on the Observer Pattern for keeping my UI up to date but I still can't see the use for it.. Even if in my particular object notifies my MainActivity then runs the update(); method I still wouldn't be able to use the Pet object to pull the update values as the object is created in Oncreate...and I just can't create a new object because then the variables will be different..this is my implementation and it doesn't seem to work.

Observer/MainActivity

package com.grim.droidchi;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements Observer, OnClickListener {
    private static final String TAG = "VPET";
    private static final String APP_PREFS = "VPET";
    private static final int REQUEST_CODE = 1;
    Boolean isAlive = false;
    TextView happiness_display, health_display, hunger_display, level_display;
    Button PunchPet, UpdateHunger;
    public static Pet pet = new Renamon();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = getSharedPreferences("APP_PREFS",
                MODE_PRIVATE);

        WebView myWebView = (WebView) findViewById(R.id.pet_display);
        myWebView.loadUrl("file:///android_asset/renamon.gif");
        myWebView.setInitialScale(10000);
        myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);


        PunchPet = (Button) findViewById(R.id.PunchPet);
        UpdateHunger = (Button) findViewById(R.id.UpdateHunger);
        final TextView hunger_display = (TextView) findViewById(R.id.hunger_display);
        TextView happiness_display = (TextView) findViewById(R.id.happiness_display);
        TextView level_display = (TextView) findViewById(R.id.level_display);
        TextView health_display = (TextView) findViewById(R.id.health_display);

        hunger_display.setText(Integer.toString(pet.getHunger()));
        health_display.setText(Integer.toString(pet.getHP()));
        level_display.setText(Integer.toString(pet.getLVL()));
        happiness_display.setText(Integer.toString(pet.getHappy()));


        Intent intent = new Intent(this, Gameloop.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(), REQUEST_CODE, intent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + (5 * 1000), 1800000, pendingIntent);
        // 1800000 ms = 30 mins

        pet.feed();
        pet.addObserver(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected void onPause() {


        super.onPause();
    }

    @Override
    public void update(Observable o, Object data) {

        hunger_display.setText(Integer.toString(pet.getHunger()));
        health_display.setText(Integer.toString(pet.getHP()));
        level_display.setText(Integer.toString(pet.getLVL()));
        happiness_display.setText(Integer.toString(pet.getHappy()));
        Log.d(TAG, "UPDATED FROM OBSERVER");

    }

    @Override
    public void onClick(View v) {
        if (v == PunchPet) {
            pet.setHP(500);
            Toast.makeText(getApplicationContext(), "PUNCHPET", Toast.LENGTH_SHORT).show();
            health_display.setText(Integer.toString(pet.getHP()));
    }else {

    }



    }

}

Observable/Pet

package com.grim.droidchi;

import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import android.util.Log;

public class Pet extends Observable implements PetInterface {
    protected Set<Observer> observers;
    private static final String TAG = "VPET";
    private int Health = 100;
    @Override
    public void addObserver(Observer o) {
        observers.add(o); 
        super.addObserver(o);
    }

    @Override
    public void notifyObservers() {
        observers.notify();
        super.notifyObservers();
    }

    @Override
    public synchronized void deleteObserver(Observer o) {
        observers.remove(o);
        super.deleteObserver(o);
    }

    private int Happiness = 10;
    private int Level = 1;
    private int Hunger = 0;
    private int Exp = 0;
    private String Name;
    private Boolean isAlive = true;
    private Boolean isSick = false;

    public void setHP(int hp) {
        this.Health = hp;
        notifyObservers(hp);
    }

    public void setLVL(int lvl) {
        this.Level = lvl;
        notifyObservers(lvl);
    }

    public void setXP(int xp) {
        this.Exp = xp;
        notifyObservers(xp);
    }

    public void setHunger(int hunger) {
        this.Hunger = hunger;
        notifyObservers(hunger);
    }

    public void setHappy(int happy) {
        this.Happiness = happy;
        notifyObservers(happy);
    }

    public int getHP() {

        return Health;
    }

    public int getLVL() {

        return Level;
    }

    public int getXP() {

        return Exp;
    }

    public int getHunger() {

        return Hunger;
    }

    public int getHappy() {

        return Happiness;
    }

    public boolean isAlive() {
        return isAlive;

    }

    public boolean isSick() {
        return isSick;

    }

    @Override
    public void sleep() {
        // TODO Auto-generated method stub

    }

    @Override
    public void clean() {
        // TODO Auto-generated method stub

    }

    @Override
    public void feed() {
        Log.d(TAG, "FEEDING FROM INTERFACE THING");

    }

    @Override
    public void passtime() {

    }

}
like image 558
Pheonix2105 Avatar asked Feb 25 '13 14:02

Pheonix2105


People also ask

What is difference between observable and observer in Android?

Observer : Any object that wishes to be notified when the state of another object changes. Observable : Any object whose state may be of interest, and in whom another object may register an interest.

What is Android observer?

In Android, the observer pattern is implemented by using the class ViewModel and the class LiveData / StateFlow. If you want to have 3 different screens that observe a single object for changes. You need to have 3 Fragments that share the same Activity and the same ViewModel.

What does an observer do in Android Studio?

An observer, which is an object that receives notifications from a provider. An observer is a class or structure that implements the IObserver<T> interface. The observer must implement three methods, all of which are called by the provider: IObserver<T>.

How does an observable work android?

An observable object can have one or more observers. An observer may be any object that implements interface Observer . After an observable instance changes, an application calling the Observable 's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.


2 Answers

First, I wouldn't recommend overriding addObserver or removeObserver in your observable object. The API does a really good job of implementing this (unless you want some specific functionality).

Second, the method notifyObservers() is overloaded so that you can pass it an object, IE notifyObservers(Object obj). If you pass it your Pet, notifyObservers(this), then you will have a reference to your Pet object that is being observed.

I think this is your question but please correct me if I am wrong.

EDIT: To clarify, my answer is contingent upon you using the Observable class in the Java API here.

Upon further review, you should already have a reference to the Pet object that called the update method of the Observer

like image 112
nattyddubbs Avatar answered Nov 15 '22 18:11

nattyddubbs


Your pet is not accessible in other methods because its not defined at global level.

You should define Pet pet = new Renamon(); outside of onCreate method.

like image 26
waqaslam Avatar answered Nov 15 '22 18:11

waqaslam