I am new to android studio, I am making an app that gets the json of a field in thingspeak, but I don’t know how can I make an auto refresh to the data I get every second. Can you please help me?
public class MainActivity extends AppCompatActivity { private TextView mTextViewResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextViewResult = findViewById(R.id.text_view_result); OkHttpClient client = new OkHttpClient(); // Read field url from thingspeak String url = "https://api.thingspeak.com/channels/XXXXXXX/fields/1.json?api_key=XXXXXXXXXXXXX&results=2"; Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException { if (response.isSuccessful()) { // this is what I want to refresh every second final String myResponse = response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mTextViewResult.setText(myResponse); } }); } } }); } }
Advertisement
Answer
I found a solution finally, I placed the data request inside the following code and it worked perfectly:
final Handler handler = new Handler(); Runnable refresh = new Runnable() { @Override public void run() { // data request handler.postDelayed(this, 5000); } }; handler.postDelayed(refresh, 5000);