我需要更新数据,例如每 15 秒更新一次。最正确的方法是什么,我尝试了处理程序,但它不起作用,也许我做错了什么。
我该如何实现这个?
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.sumb.AllTecTag.TecOneTag;
import com.example.sumb.R;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class TecOne extends Fragment {
private TextView city_p_forward;
private TextView city_t_forward;
private TextView city_q_forward;
private TextView city_w_forward;
private TextView east_p_return;
public TecOne() {}
private void jsonTecOne(){
final ObjectMapper mapper = new ObjectMapper();
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
try {
final TecOneTag tecOneTag = mapper.readValue(new URL("https://some-address.json"),TecOneTag.class);
handler.post(new Runnable() {
@Override
public void run() {
city_p_forward.setText(tecOneTag.getCity_P_T1());
city_t_forward.setText(tecOneTag.getCity_T_T1());
city_q_forward.setText(tecOneTag.getCity_Q_T1());
city_w_forward.setText(tecOneTag.getCity_W_T1());
east_p_return.setText(tecOneTag.getEast_P_T2());
}
});
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.fragment_tec_one, container, false);
city_p_forward = RootView.findViewById(R.id.city_p_forward);
city_t_forward = RootView.findViewById(R.id.city_t_forward);
city_q_forward = RootView.findViewById(R.id.city_q_forward);
city_w_forward = RootView.findViewById(R.id.city_w_forward);
east_p_return = RootView.findViewById(R.id.east_p_return);
jsonTecOne();
return RootView;
}
}
我通过以下示例做到了:https://www.codexpedia.com/java/jackson-parser-example-in-android/
最佳答案
创建 1 个单独的方法来获取数据,
类似这样的
private void getData(){
//retrieve your data here
//also update your data here in TextViews and all
}
现在您可以使用 handler
每 15 秒更新一次数据,例如
final Handler handler = new Handler();
handler.post(r);
final Runnable r = new Runnable() {
public void run() {
//Do something after 15000ms or 15sec
//call you getData() method here
getData();
//now call the runnable again after 15sec
//you can also add some condition to stop this
handler.postDelayed(this, 15000); // 15000 = 15 sec
}
};
希望这会有所帮助!
关于java - android studio 每 X 秒自动刷新线程中的数据 json url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59978413/