2015年9月14日 星期一

[Android] Implementing Callbacks when JSON operation is done

More often then not we find ourselves in a situation where we must wait for an action to be completed before performing another task, for example wait for JSON to finish parsing before performing a task.

In this case, the easiest way would be to implement a callback: when JSON is done parsing, set a flag to true.

Within your operation class, for example OperationJSON.class
Create an Interface:
1
2
3
interface OnParseDataCompleted{
    void onTaskCompleted();
}


initialize a listener and a setter/getter for isCompleted flag and execute onTaskCompleted when the task is done:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public boolean isCompleted = false;

public boolean isCompleted() {
    return isCompleted;
}

public void setIsCompleted(boolean isCompleted) {
    this.isCompleted = isCompleted;
}

private void parseTheData(String requestUrl, final JSONObject jsonObj) {
    new AsyncTask<String, Void, JSONObject>() {
        private OnParseDataCompleted listener = new OnParseDataCompleted() {
            @Override            
            public void onTaskCompleted() {
                setIsCompleted(true);
            }
        };

        @Override        
        protected JSONObject doInBackground(String... urls) {
            //omitted
        }

        @Override        
        protected void onPostExecute(JSONObject jsonObjRecv) {
                listener.onTaskCompleted();
            }
        }
    }.execute(requestUrl);
}




At this point, whenever this AsyncTask is completed, it will execute listener.onTaskCompleted(), which will set isCompleted to true;

To use this flag, simply check this flag wherever necessary:

沒有留言:

張貼留言