我是android开发的新手。我正在学习它。我可以使用Recyclerview在listview中获取json数据。现在我想要包含swiperRefreshLayout,因此服务器中的任何更新也会在刷新时显示。我在json中搜索关于swiperRefreshLayout的教程,但这不起作用。我尝试使用DefaultHttpClient,但我无法理解这个想法。
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health);
mRecyclerView = findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
}
});
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://fitandfineindustries.com/healthapi.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("info");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String creatorName = hit.getString("heading");
String img = hit.getString("img");
String imageUrl = img.length() == 0 ? "file:///android_asset/fitandfineindustries.jpg" : "http://fitandfineindustries.com/images/plan/"+img;
mExampleList.add(new NewsItem(imageUrl, creatorName));
}
mNewsAdapter = new NewsAdapter(HealthActivity.this, mExampleList);
mRecyclerView.setAdapter(mNewsAdapter);
mNewsAdapter.setOnItemClickListener(HealthActivity.this);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
答案 0 :(得分:2)
在刷新调用时,你的parseJSON()确保在此之前你需要清除你的数组。
SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mExampleList.clear()
parseJSON();
}
});
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
答案 1 :(得分:0)
SwipeLayout与服务器无关(网络呼叫)。当用户拉动刷新时,调用SwipeRefreshLayout.OnRefreshListener的onRefresh()。就是这样,就是SwipeRefreshLayout所做的一切。
这可能会对您有所帮助 -
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//call the parseJSON() function here like this.
parseJSON();
// call the setRefreshing(true) function to show
// the circular rotating refresh icon
mSwipeRefreshLayout.setRefreshing(true);
}
});
//Don't forget to hide the refreshing icon when your server call ends like this.
//mSwipeRefreshLayout.setRefreshing(false);