Volley解析JSON并填充RecyclerView求助(JSON新手)
解决Volley解析JSON数组并填充RecyclerView的问题
我看了你的代码,确实有几个小问题导致JSON解析失败,下面帮你一步步修正:
先说说代码里的关键错误:
- 你在
onResponse里用了未定义的变量s和jsonArray,应该用回调参数response来遍历JSON数组 - 循环内重复调用
loadingPop.dismiss(),会导致加载框在第一次循环就消失,应该在所有数据解析完成后再关闭 - 冗余的剪贴板操作可以暂时去掉,避免干扰核心逻辑
- 异常捕获的提示可以更友好一点
修正后的完整代码
public class OnGoingDetails extends AppCompatActivity { private RecyclerView mRecyclerView; private EpisodeListAdapter mExampleAdapter; private ArrayList<EpisodeListModel> mExampleList; private RequestQueue mRequestQueue; private ProgressDialog loadingPop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ongoing_detail); // 初始化RecyclerView mRecyclerView = findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mExampleList = new ArrayList<>(); mRequestQueue = Volley.newRequestQueue(this); // 初始化加载对话框 loadingPop = new ProgressDialog(this); loadingPop.setTitle("Loading..."); loadingPop.setMessage("Please wait retrieving data from server"); loadingPop.setCanceledOnTouchOutside(false); loadingPop.show(); // 获取传递过来的API地址 Bundle extra = getIntent().getExtras(); if (extra != null) { String url = extra.getString("ID"); if (url != null && !url.isEmpty()) { fetchEpisodeData(url); } else { Toast.makeText(this, "Invalid API URL", Toast.LENGTH_SHORT).show(); loadingPop.dismiss(); } } else { Toast.makeText(this, "No data received from previous activity", Toast.LENGTH_SHORT).show(); loadingPop.dismiss(); } } private void fetchEpisodeData(String url) { JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { // 遍历JSON数组 for (int i = 0; i < response.length(); i++) { JSONObject jo = response.getJSONObject(i); String episodeId = jo.getString("id"); // 添加数据到列表 mExampleList.add(new EpisodeListModel(episodeId)); } // 初始化适配器并设置到RecyclerView mExampleAdapter = new EpisodeListAdapter(OnGoingDetails.this, mExampleList); mRecyclerView.setAdapter(mExampleAdapter); // 所有操作完成后关闭加载框 loadingPop.dismiss(); Toast.makeText(OnGoingDetails.this, "Data loaded successfully", Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(OnGoingDetails.this, "JSON Parse Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); loadingPop.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { loadingPop.dismiss(); String errorMsg; if (error instanceof NetworkError || error instanceof NoConnectionError) { errorMsg = "Oops. Network error!"; } else if (error instanceof ServerError) { errorMsg = "Oops. Server error!"; } else if (error instanceof AuthFailureError) { errorMsg = "Oops. Authentication error!"; } else if (error instanceof ParseError) { errorMsg = "Oops. Parse error!"; } else if (error instanceof TimeoutError) { errorMsg = "Oops. Timeout error!"; } else { errorMsg = "Unknown error occurred!"; } Toast.makeText(OnGoingDetails.this, errorMsg, Toast.LENGTH_LONG).show(); } }); // 设置重试策略 request.setRetryPolicy(new DefaultRetryPolicy( 10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); mRequestQueue.add(request); } }
关键修改点说明:
- 拆分代码到单独方法:把网络请求逻辑抽成
fetchEpisodeData方法,让代码更清晰易维护 - 空值判断:增加了对Bundle和URL的空值检查,避免空指针异常
- 修复JSON遍历变量:用回调参数
response代替未定义的jsonArray,移除了未定义的s变量 - 调整加载框时机:只在所有数据解析完成或出错时关闭加载框,避免提前消失
- 优化错误提示:统一错误信息处理,让提示更准确
- 移除冗余代码:去掉了和核心逻辑无关的剪贴板操作,避免干扰
另外,确保你的EpisodeListModel类正确定义了接收id的构造方法,比如:
public class EpisodeListModel { private String episodeId; public EpisodeListModel(String episodeId) { this.episodeId = episodeId; } public String getEpisodeId() { return episodeId; } }
还有你的EpisodeListAdapter要正确绑定数据到RecyclerView的Item布局,比如在onBindViewHolder里获取数据并设置到TextView等控件上。
内容的提问来源于stack exchange,提问作者RTH Creating Studio
相关产品推荐
相关产品推荐

