我正在创建一个Android应用程序,它从API中提取信息并将其显示在Recyclerview中。但是一切正常,当应用程序打开时我只有1 GET request
(使用Volley)。
我想让回收站视图中的信息每5秒更新一次。我是Java的新手,无法在线找到任何其他问题或资源,解释如何最有效地保持活动API中的信息最新。我应该每隔5秒Get Request
,如果是这样,你最好如何实现这一点?如果没有,是否有更合适的方式。
任何反馈都会对我有所帮助,而且我确定一群未来的开发者。我目前的代码是为了参考。
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "https://summerproject17.herokuapp.com/api/request/";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("results");
for(int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("room"),
o.getString("request"),
o.getString("time")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
MyAdapter.Java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context)
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewHead.setText(listItem.getHead());
holder.textViewDesc.setText(listItem.getDesc());
}
@Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewDesc;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
}
答案 0 :(得分:0)
请尝试此解决方案
"3.14159265358979323846"