1. Are you ready for the Galaxy S20? Here is everything we know so far!

How is this interface implemented?

Discussion in 'Android Development' started by Rascalsailor, Apr 20, 2020.

  1. Rascalsailor

    Rascalsailor Lurker
    Thread Starter

    Hi all. I wrote a simple weather app which goes fetches data from Openweathermap's API in Json format. I used an Aynctask to fetch the data, using ideas from online (as we all do!)
    All works ok, but I am trying to get a better understanding of the callback implementation (similar to the one at http://smartandroidians.blogspot.com/2015/03/how-to-use-callback-or-interface-pass.html)
    In particular, I am trying to understand how is the interface is implemented without the keyword 'implements' anywhere?
    The Async thread:

    Code (Java):
    1. class MyTask extends AsyncTask {
    2. public interface OnUpdateListener {
    3. public void onUpdate(MyObject obj);
    4. }
    5. OnUpdateListener listener;
    6. MyTask() {
    7. }
    8. public void setUpdateListener(OnUpdateListener listener) {
    9. this.listener = listener;
    10. }
    11. MyObject doInBackground() {
    12. return obj;
    13. }
    14. onPostExecute(MyObject obj) {
    15. if (listener != null) {
    16. listener.onUpdate(obj);
    17. }
    18. }
    And in the main thread:
    Code (Java):
    1. yActivity extends Activity {
    2. void onCreate (Bundle savedInstanceState) {
    3. super.onCreate(savedInstanceState);
    4. MyTask  task = new MyTask();
    5. task. setUpdateListener(new MyTask. OnUpdateListener() {
    6. public void onUpdate(MyObject obj) {
    7. .....
    8. }
    9. });
    10. task.execute();
    11. }
    12. }
    Then in the code that I did:
    Code (Java):
    1. public class fetchData extends AsyncTask<Void, String, String> {
    2.     //------------added--------------
    3.     public interface AsyncResponse {
    4.         void processFinish(String output);
    5.     }
    6.     public AsyncResponse  delegate = null;//Call back interface
    7.  
    8.     public fetchData(AsyncResponse asyncResponse) {
    9.         delegate = asyncResponse;//Assigning call back interface through constructor
    10.     }
    11. //---------------------------------------
    12.     String data = "";
    13.     String dataParsed = "";
    14.     String singleParsed = "";
    15.     String iconValue = "";
    16.  
    17.  
    18.  
    19.     protected String doInBackground(Void...voids) {
    20.  
    21.         try {
    Thanks all
    Russell
     


Loading...

Share This Page

Loading...