-1

I am developing a simple android application that receive a json string from a background service via websocket. The json data is changed overtime. For example, the json string is:

{"app":"events","command":"handleEvents","args":{"eventId":16,"name":"X2_PA_STATE","params":[0]}}

Since the params value is changing all the time, how do I display it via TextView and auto update its value? I have tried event listener but it seems not to work.

Blairg23
  • 11,334
  • 6
  • 72
  • 72
S Huynh
  • 3
  • 2
  • 1
    What event listener have you tried? If you're listening to a change via the background service, you should handle your updating within it. – daedsidog Oct 09 '18 at 17:33
  • If you are trying to update data through background service, it would be better to Bind your service into your activity/fragment use ServiceConnection to communicate or you can BroadcasteReceiver . – gkondati Oct 09 '18 at 17:41
  • I created a custom listener, but I cant seems to post the code here – S Huynh Oct 09 '18 at 17:43
  • the background service is not a part of my application, it is an external apps that send data via websocket where my application listen to and extract that data to display – S Huynh Oct 09 '18 at 17:51

2 Answers2

0

Android has a built-in JSON Parser.

JSONObject obj = new JSONObject(<res_json_string>);
String app = obj.optString("app");
String command = obj.optString("command");
JSONObject args = obj.optJSONObject("args");
String eventId = args.optString("eventId");
String name = args.optString("name");
JSONArray p = args.optJSONArray("params");
ArrayList<String> params = new ArrayList<>();
for(int i = 0; i < p.length; i++){
   params.add(p.get(i));
}

Since you are in background Service you have to use Handler or BroadcastReceiver to achieve this task. (Only from UI thread you can update UI)

see this link for example Updating UI from Service

Hope this helps, Happy coding!!

Jayanth
  • 5,954
  • 3
  • 21
  • 38
  • Sorry that I am not being clear about the so called "background service". it is not part of the android Eco system. it is an external application running along with. I am able to parse the JSON, but dont know how to display it and update when the value changed – S Huynh Oct 09 '18 at 18:10
0

If I understand correctly, you have some kind of websocket service, not related with Android at all, that sends data. The part you may be missing is adding a websocket implementation to your Android app, to listen your websocket service and parse the data. Then, you could just call textview.setText() method to update the textview value every time you receive data from the websocket.

In that case, take a look to OkHttp WebSocket implementation

https://square.github.io/okhttp/3.x/okhttp/okhttp3/WebSocket.html

Daniel Luque
  • 116
  • 1
  • 8