我尝试使用Volley库在片段中实现回收器视图。 数据从服务器成功加载和记录,但在回收器片段中根本不显示。
请求获取数据并记录它,但片段中没有任何呈现。没有XML错误。
HitVideoFragment.java
public class HitVideoFragment extends Fragment {
private RecyclerView recyclerView;
private HitVideoAdapter adapter;
private List<HitVideo> hitVideoList = new ArrayList<HitVideo>();
public HitVideoFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hit_video, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//Initializing Views
recyclerView = (RecyclerView) this.getActivity().findViewById(R.id.hitvideo_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new HitVideoAdapter(hitVideoList);
recyclerView.setAdapter(adapter);
//Calling method to get data
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this.getActivity(),"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(AppConfig.URL_HIT_VIDEOS,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("Some tag", "onResponse: "+response.toString());
hitVideoList = new ArrayList<HitVideo>();
for(int i = 0; i<response.length(); i++) {
HitVideo hitVideo = new HitVideo();
JSONObject json = null;
try {
json = response.getJSONObject(i);
hitVideo.setTitle(json.getString("name"));
hitVideo.setUrl(json.getString("url"));
hitVideo.setUsername(json.getString("user_id"));
hitVideo.setHits(json.getInt("hits"));
} catch (JSONException e) {
e.printStackTrace();
}
hitVideoList.add(hitVideo);
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Hit Video", "Error: " + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
Context _context = getActivity().getApplicationContext();
SharedPreferences pref;
String token;
if (_context != null) {
pref = _context.getSharedPreferences(Config.PREF_NAME, Config.PRIVATE_MODE);
if (pref != null) {
token = pref.getString(Config.USER_TOKEN, null);
headers.put("Authorization", "Bearer " + token);
}
}
return headers;
}
};
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this.getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
这不会引发任何例外。模型和适配器正在完成它们的工作。提前致谢。