I can't figure out how to get live updates in android from a json api that updates every 2-3 seconds. I've managed to download the JSON code and then create some arrays and log them, but I the values from the json api change every 2-3 seconds and I have no idea how to redownload the JSON. Thanks in advance for your help!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try{
result = task.execute("thelinkIuse").get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
while (true) {
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
return "Failed";
}
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray arr = new JSONArray(result);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
symbols.add(jsonPart.getString("symbol"));
bids.add(jsonPart.getString("bid"));
asks.add(jsonPart.getString("ask"));
}
Log.i("Symbols", String.valueOf(symbols));
Log.i("Bids", String.valueOf(bids));
Log.i("Asks", String.valueOf(asks));
} catch (JSONException e) {
e.printStackTrace();
Log.i("failed", "failed");
}
}
}
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try{
result =new DownloadTask().execute("thelinkIuse").get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
},0,5000);
This will call the asynctask every 5 seconds, thus fetching the updated JSON string