當我的服務器更新新資料并且用戶滑動以重新加載時,它對我不起作用。我有fragment_home.xml和Home.java來顯示資料。現在,我該怎么做?我的 XML 檔案運行良好,但我不明白在 Java 中該做什么?您能否通過編輯我的代碼來發布答案以更好地理解?
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@ id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragments.Home"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@ id/bar"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@ id/recyclerviewid">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
主頁.java
public class Home extends Fragment {
private final String JSON_URL = "https://mywebsite.org/news/api.php";
private JsonArrayRequest request ;
private RequestQueue requestQueue ;
private List<Anime> lstAnime ;
private RecyclerView recyclerView ;
ProgressBar loading;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
loading = (ProgressBar)root.findViewById(R.id.bar);
loading.setMax(100);
lstAnime = new ArrayList<>() ;
recyclerView = root.findViewById(R.id.recyclerviewid);
jsonrequest();
return root;
}
private void jsonrequest() {
request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
loading.setVisibility(View.GONE);
JSONObject jsonObject = null ;
for (int i = 0 ; i < response.length(); i ) {
try {
jsonObject = response.getJSONObject(i) ;
Anime anime = new Anime() ;
anime.setName(jsonObject.getString("title"));
anime.setDescription(jsonObject.getString("description"));
anime.setDate(jsonObject.getString("date"));
anime.setCategorie(jsonObject.getString("category"));
anime.setAuthor(jsonObject.getString("admin"));
anime.setImage_url(jsonObject.getString("thumbnail"));
lstAnime.add(anime);
} catch (JSONException e) {
e.printStackTrace();
}
}
setuprecyclerview(lstAnime);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//This indicates that the request has either time out or there is no connection
Toast.makeText(getActivity(), "TimeOut...! No Internet",
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
// Error indicating that there was an Authentication Failure while performing the request
Toast.makeText(getActivity(), "Failed To Receive Data",
Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
//Indicates that the server responded with a error response
Toast.makeText(getActivity(), "Our Server Under Maintenance",
Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError) {
//Indicates that there was network error while performing the request
Toast.makeText(getActivity(), "Network Not Responding",
Toast.LENGTH_LONG).show();
} else if (error instanceof ParseError) {
// Indicates that the server response could not be parsed
Toast.makeText(getActivity(), "Please Reload Again!",
Toast.LENGTH_LONG).show();
}
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
private void setuprecyclerview(List<Anime> lstAnime) {
RecyclerViewAdapter myadapter = new RecyclerViewAdapter(getActivity(),lstAnime);
recyclerView.setAdapter(myadapter);
// grid columns is 2
GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
// 0 is first one and 9 is first one all of others are 2 columns
if (position == 0 || position == 9) {
return 2;
}
return 1;}
});
recyclerView.setItemAnimator(null);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(myadapter);
recyclerView.setLayoutManager(manager);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
對不起,我的英語不好。提前致謝。
uj5u.com熱心網友回復:
如果您想在服務器上更新資料后立即更新應用程式中的資料,那么您應該使用 Web-Sockets 而不是 API,因為 API 只有在您使用正確的憑據點擊它時才會給出回應。
uj5u.com熱心網友回復:
我沒有看到您初始化SwipeRefreshLayoutxml 檔案中包含的內容的地方。您的片段應該實作SwipeRefreshLayout.OnRefreshListener并覆寫該onRefresh()方法以觸發您的網路請求。也不要忘記在使用完成網路請求時關閉 SwipeRefreshLayout 加載器swipeRefreshLayout.setRefreshing(boolean)
您可以查看檔案了解更多詳情:https : //developer.android.com/training/swipe
這是實作了 SwipeRefreshLayout 的片段。
public class Home extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private final String JSON_URL = "https://mywebsite.org/news/api.php";
private JsonArrayRequest request ;
private RequestQueue requestQueue ;
private List<Anime> lstAnime ;
private RecyclerView recyclerView ;
ProgressBar loading;
private SwipeRefreshLayout swipeRefreshLayout; //declare SwipeRefreshLayout
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
swipeRefreshLayout = (SwipeRefreshLayout)root.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener(this); //add refresh listener
loading = (ProgressBar)root.findViewById(R.id.bar);
loading.setMax(100);
lstAnime = new ArrayList<>() ;
recyclerView = root.findViewById(R.id.recyclerviewid);
jsonrequest();
return root;
}
private void jsonrequest() {
request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
swipeRefreshLayout.setRefreshing(false); //Dismiss SwipeRefreshLayout loader
loading.setVisibility(View.GONE);
JSONObject jsonObject = null ;
for (int i = 0 ; i < response.length(); i ) {
try {
jsonObject = response.getJSONObject(i) ;
Anime anime = new Anime() ;
anime.setName(jsonObject.getString("title"));
anime.setDescription(jsonObject.getString("description"));
anime.setDate(jsonObject.getString("date"));
anime.setCategorie(jsonObject.getString("category"));
anime.setAuthor(jsonObject.getString("admin"));
anime.setImage_url(jsonObject.getString("thumbnail"));
lstAnime.add(anime);
} catch (JSONException e) {
e.printStackTrace();
}
}
setuprecyclerview(lstAnime);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false); //Dismiss SwipeRefreshLayout loader
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//This indicates that the request has either time out or there is no connection
Toast.makeText(getActivity(), "TimeOut...! No Internet",
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
// Error indicating that there was an Authentication Failure while performing the request
Toast.makeText(getActivity(), "Failed To Receive Data",
Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
//Indicates that the server responded with a error response
Toast.makeText(getActivity(), "Our Server Under Maintenance",
Toast.LENGTH_LONG).show();
} else if (error instanceof NetworkError) {
//Indicates that there was network error while performing the request
Toast.makeText(getActivity(), "Network Not Responding",
Toast.LENGTH_LONG).show();
} else if (error instanceof ParseError) {
// Indicates that the server response could not be parsed
Toast.makeText(getActivity(), "Please Reload Again!",
Toast.LENGTH_LONG).show();
}
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}
private void setuprecyclerview(List<Anime> lstAnime) {
RecyclerViewAdapter myadapter = new RecyclerViewAdapter(getActivity(),lstAnime);
recyclerView.setAdapter(myadapter);
// grid columns is 2
GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
// 0 is first one and 9 is first one all of others are 2 columns
if (position == 0 || position == 9) {
return 2;
}
return 1;}
});
recyclerView.setItemAnimator(null);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(myadapter);
recyclerView.setLayoutManager(manager);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
@Override
public void onRefresh() {
//Whatever is here will be executed when the user swipe to refresh
jsonrequest();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338822.html
標籤:安卓 数组 json android-recyclerview android-volley
上一篇:輸入有效會員號時不執行回傳陳述句
