RecyclerView Context传参错误排查:JSON列表实现问题求助
问题解决方案
核心错误修复
报错的直接原因是在GetUrlData内部类的onPostExecute方法中,new LinearLayoutManager(this, ...)里的this指代的是GetUrlData实例而非WeatherActivity上下文。LinearLayoutManager构造方法需要Context类型参数,只需将this替换为WeatherActivity.this即可解决该参数不匹配问题。
其他关键代码优化
除上述错误外,代码中还有几个会导致功能异常或性能问题的点,需一并修复:
- 将
ArrayList<Condition>初始化移到循环外部,确保所有数据都添加到同一个列表 - 提前获取RecyclerView实例,避免循环中重复调用
findViewById - 仅在所有数据加载完成后,一次性设置LayoutManager和Adapter
修正后的WeatherActivity代码
public class WeatherActivity extends AppCompatActivity { private RecyclerView rcView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather); // 提前获取RecyclerView实例 rcView = findViewById(R.id.recyclerView2); int District = getIntent().getIntExtra("District", -1); String latitude=""; String longitude=""; switch (District) { case 0: latitude = "55.753600"; longitude = "37.621184"; break; case 1: latitude = "55.838390"; longitude = "37.525774"; break; case 2: latitude = "55.854875"; longitude = "37.632565"; break; case 3: latitude = "55.787715"; longitude = "37.775631"; break; case 4: latitude = "55.692019"; longitude = "37.754592"; break; case 5: latitude = "55.622014"; longitude = "37.678065"; break; case 6: latitude = "55.662735"; longitude = "37.576187"; break; // 修复原代码缺少的break,避免坐标被后续case覆盖 case 7: latitude = "55.778003"; longitude = "37.443533"; break; case 8: latitude = "55.829370"; longitude = "37.451555"; break; case 9: latitude = "55.987583"; longitude = "37.194250"; break; case 10: latitude = "55.355802"; longitude = "37.146999"; break; case 11: latitude = "55.594351"; longitude = "37.371452"; break; default: break; } String url = "https://api.open-meteo.com/v1/forecast?latitude=" + latitude + "&longitude=" + longitude + "&hourly=temperature_2m,relative_humidity_2m,apparent_temperature,precipitation_probability,snowfall,cloud_cover,wind_speed_10m&wind_speed_unit=ms&timezone=Europe%2FMoscow&forecast_days=1"; new GetUrlData().execute(url); } private class GetUrlData extends AsyncTask<String,String,String> { @Override protected String doInBackground(String... strings) { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url1 = new URL(strings[0]); connection =(HttpURLConnection) url1.openConnection(); connection.connect(); InputStream stream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine())!=null){ buffer.append(line).append("\n"); } return buffer.toString(); } catch (MalformedURLException e){ e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(connection!=null){ connection.disconnect(); } if(reader!=null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } @Override protected void onPostExecute(String result){ super.onPostExecute(result); if(result!=null) { try { JSONObject object = new JSONObject(result); JSONArray timeArray = object.getJSONObject("hourly").getJSONArray("time"); JSONArray temperatureArray = object.getJSONObject("hourly").getJSONArray("temperature_2m"); JSONArray humidityArray = object.getJSONObject("hourly").getJSONArray("relative_humidity_2m"); JSONArray precipitationArray = object.getJSONObject("hourly").getJSONArray("precipitation_probability"); JSONArray cloudArray = object.getJSONObject("hourly").getJSONArray("cloud_cover"); JSONArray windSpeedArray = object.getJSONObject("hourly").getJSONArray("wind_speed_10m"); JSONArray snowArray = object.getJSONObject("hourly").getJSONArray("snowfall"); // 循环外初始化列表,收集所有数据 ArrayList<Condition> conditions = new ArrayList<>(); for (int i = 0; i < timeArray.length(); i++) { try { String time = timeArray.getString(i); SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); Date date = inputFormat.parse(time); String outputString = outputFormat.format(date); String temperature = temperatureArray.getString(i); String humidity = humidityArray.getString(i); double precipitation = precipitationArray.getDouble(i); double cloud = cloudArray.getDouble(i); String windSpeed = windSpeedArray.getString(i); String snowfall = snowArray.getString(i); conditions.add(new Condition(outputString, temperature, humidity, precipitation, cloud, windSpeed, snowfall)); } catch (ParseException e) { e.printStackTrace(); } } // 所有数据收集完成后,一次性设置Adapter和LayoutManager WeatherAdapter adapter = new WeatherAdapter(conditions); rcView.setLayoutManager(new LinearLayoutManager(WeatherActivity.this, LinearLayoutManager.VERTICAL, false)); rcView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } } } } }
补充说明
- 修复了
case 6中缺失的break语句,避免坐标被后续case覆盖 - 替换上下文参数为
WeatherActivity.this,解决LinearLayoutManager构造方法参数错误 - 优化数据收集和RecyclerView初始化逻辑,确保所有数据正确显示
内容的提问来源于stack exchange,提问作者Никита Стрыгин
相关产品推荐
相关产品推荐

