Dan
Dan

Reputation: 1174

Call method from another object-java

I'm doing some Android development and I have an object, which doing a specific task. When that task is done I need to inform my main method (Main Activity), which is constantly running, that the process has been finished and pass some information about it.

This may sound a bit unclear, so I'll give you an example:
Take a look at the setOnClickListener() method in Android:

 Button button = (Button) findViewById(R.id.button1);
            button.setOnClickListener(new OnClickListener() {
                    //This method is called on click
                    @Override
                    public void onClick(View v) {
                      //The View is passed in an anonymous inner class 
                    }
            });

It waits for a button to be clicked and calls the onClick(View v) method. I am seeking to achieve the same code structure.

How to do this?

Upvotes: 0

Views: 76

Answers (2)

Chad Bingham
Chad Bingham

Reputation: 33856

You mentioned "process". If you are truly doing something in a different process, then you need to look at interprocess communications (IPC). Otherwise, you can use an interface:

Create a class called MyListener:

public interface MyListener {
    void onComplete();
}

In your class that will notify your activity:

MyListener myListener;

public void setMyListener(MyListener myListener){
  this.myListener = myListener;
}

Then, when you are ready to notify your main activity, call this line:

myListener.onComplete();

Last, in your MainActivity implement MyListener:

public class MyListener extends Activity implements MyListener {
     ///other stuff

     @Override
     public void onComplete(){
        // here you are notified when onComplete it called
     }
}

Hope this helps. Cheers.

Upvotes: 1

wasyl
wasyl

Reputation: 3506

This is exactly Listener pattern that you use with views in android. What you want to do is declare an interface in your class that's doing the job, and pass an instance of this interface. Raw example:

TaskDoer.java:

public class TaskDoer {
  public interface OnTaskDoneListener {
    void onDone(Data data);
  }

  public void doTask(OnTaskDoneListener listener) {
    // do task...
    listener.onDone(data);
  }
}

Activity:

public void doTaskAndGetResult() {
  new TaskDoer().doTask(new TaskDoer.OnTaskDoneListener() {
      public void onDone(Data data) {
         // do something
      }
  }
}

Upvotes: 1

Related Questions