Recyclerview 适配器错误:Android Studio 中的 Arraylist 大小为零

Posted

技术标签:

【中文标题】Recyclerview 适配器错误:Android Studio 中的 Arraylist 大小为零【英文标题】:Recyclerview adapter error: Arraylist size zero in Android studio 【发布时间】:2021-12-10 07:28:31 【问题描述】:

首先抱歉我的英语不好。我的问题是,我正在尝试使用 Wea​​ther API 制作天气应用程序。我想使用 recyclerview 适配器显示 5 天的预测。我将数据添加到 arraylist,我从 API 获得,它应该去我的适配器类。它需要在那里显示添加到 arraylist 的数据,但它没有,并且 arraylist 大小始终为零。

我的recyclerview类是预测的

创建

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_forecast);

    Intent intent = getIntent();
    Latitude = intent.getDoubleExtra("lat",0);
    Longitude = intent.getDoubleExtra("long",0);
    System.out.println("LATİTUDE "+Latitude+" Longitude "+Longitude);//i just experimented to 
                                                                         check if latitude and 
                                                                         longitude come
    init();


初始化()

public void init()
    arrayList = new ArrayList<>();

    forecast_back_icon = findViewById(R.id.forecast_back_icon);
    recyclerviewforecast = findViewById(R.id.RecyclerviewForecast);


    get_forecast_data(Latitude,Longitude);


    forecastAdapter = new ForecastAdapter(arrayList);
    recyclerviewforecast.setAdapter(forecastAdapter);
    recyclerviewforecast.setLayoutManager(new LinearLayoutManager(forecast.this));

    forecast_back_icon();


get_forecast_data() 函数

public void get_forecast_data(Double Lat, Double Long)

    //EXAMPLE URL
    //https://api.openweathermap.org/data/2.5/weather?lat=lat&lon=lon&appid=API%20key
   
    API_KEY_FORECAST = "c29ecfafd4a70caad8fee38d6054bfc7";
    URL_FORECAST = "https://api.openweathermap.org/data/2.5/onecall?lat="+Lat+"&lon="+Long+"&exclude=current,minutely,hourly,alerts&appid="+API_KEY_FORECAST;
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_FORECAST, null, new Response.Listener<JSONObject>() 
        @Override
        public void onResponse(JSONObject response) 
            try 

                JSONArray daily = response.getJSONArray("daily");
                for(int i=0;i<daily.length();i++)

                    String  temp = daily.getJSONObject(i).getJSONObject("temp").getString("day");
                    String feels_like = daily.getJSONObject(i).getJSONObject("feels_like").getString("day");
                    String pressure = daily.getJSONObject(i).getString("pressure");
                    String humidity = daily.getJSONObject(i).getString("humidity");
                    String wind_speed = daily.getJSONObject(i).getString("wind_speed");
                    String icon = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("icon");
                    String description = daily.getJSONObject(i).getJSONArray("weather").getJSONObject(0).getString("description");
                    arrayList.add(new RecyclerviewModel(temp,humidity,feels_like,pressure,description,wind_speed,icon));

                

            

            catch (JSONException e) 
                e.printStackTrace();

            
        

    , new Response.ErrorListener() 
        @Override
        public void onErrorResponse(VolleyError error) 

            error.printStackTrace();
        
    );
    queue.add(request);
    System.out.println("forecast class arraylist size : --> "+arrayList.size());

当我在底部检查时,arraylist 的大小为零

我的预测适配器类

 public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.MyForecastViewHolder> 

ArrayList<RecyclerviewModel> ForecastArraylist;


public ForecastAdapter(ArrayList<RecyclerviewModel> ForecastArraylist)
    this.ForecastArraylist = ForecastArraylist;
    System.out.println("ForecastAdapter arraylist size : --- > "+ForecastArraylist.size());


@NonNull
@Override
public MyForecastViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
    RecyclerviewForecastRowBinding recyclerviewForecastRowBinding = RecyclerviewForecastRowBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false);
    return new MyForecastViewHolder(recyclerviewForecastRowBinding);



@Override
public void onBindViewHolder(@NonNull MyForecastViewHolder holder, int position) 


    System.out.println("we are in onbindviewholder.... ");
    Double temperature = Double.parseDouble(ForecastArraylist.get(position).getTemperature()) - 273.15;
    System.out.println(temperature);
    Double feels_like = Double.parseDouble(ForecastArraylist.get(position).getFeels_like()) - 273.15;


    holder.binding.txtRecyclerviewTemp.setText(temperature.toString().substring(0,4)+"°");
    holder.binding.txtRecyclerviewFeelslike.setText(feels_like.toString().substring(0,4)+"°");
    holder.binding.txtRecyclerviewHumidity.setText("%"+ForecastArraylist.get(position).getHumadity());
    holder.binding.txtRecyclerviewPressure.setText(ForecastArraylist.get(position).getPressure()+"hPa");
    holder.binding.txtRecyclerviewWindSpeed.setText(ForecastArraylist.get(position).getWind_speed()+"km/h");
    holder.binding.txtRecyclerviewCloud.setText(ForecastArraylist.get(position).getDescription());
    String icon_id = ForecastArraylist.get(position).getId();
    load_weather_icon(icon_id,holder);




@Override
public int getItemCount() 
    return ForecastArraylist.size();


public class MyForecastViewHolder extends RecyclerView.ViewHolder
    private RecyclerviewForecastRowBinding binding;

    public MyForecastViewHolder(@NonNull RecyclerviewForecastRowBinding binding) 
        super(binding.getRoot());
        this.binding = binding;
    

public void load_weather_icon(String id,MyForecastViewHolder holder )

    int id1 = Integer.valueOf(id);

    if(id1>=200 && id1 <= 232)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.thunderstorm);
    
    else if(id1>=300 && id1<= 321)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
    
    else if(id1>=500 && id1<= 504)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.rain);
    
    else if(id1 == 511)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
    
    else if(id1>=520 && id1<= 531)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
    
    else if(id1>=600 && id1<= 622)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
    
    else if(id1>=701 && id1<= 781)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.mist);
    
    else if(id1 == 800 )
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.clearsky);
    
    else if(id1 == 801)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.fewclouds);
    
    else if(id1 == 802)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.scatteredclouds);
    
    else if(id1 == 803)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
    
    else if(id1 == 804)
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.brokenclouds);
    


我在我的预测适配器中看不到“我们在 onbindviewholder”

预测 xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".forecast"
android:orientation="vertical"
android:id="@+id/forecastLayout">

<com.google.android.material.appbar.AppBarLayout
    android:layout_
    android:layout_
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:id="@+id/Toolbarcities">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/toolbarconstraintforecast"
        android:layout_
        android:layout_
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <androidx.appcompat.widget.Toolbar
            android:id="@+id/MyToolbarforecast"
            android:layout_
            android:layout_
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:titleTextColor="@color/white"
            >

            <ImageView
                android:id="@+id/forecast_back_icon"
                android:layout_
                android:layout_
                android:src="@drawable/cities_back_icon"
                ></ImageView>

        </androidx.appcompat.widget.Toolbar>
    </androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.appbar.AppBarLayout>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/RecyclerviewForecast"
    android:layout_
    android:layout_ />

【问题讨论】:

感谢 Sweta Jain 的编辑 【参考方案1】:

这里的问题是,在处理 Volley 请求并填充数组列表之前,您已经使用空数组列表创建了适配器并将其分配给 Recyclerview。 有两种方法可以解决此问题。首先是创建适配器并在 Volley 请求的 OnResponse 方法中设置适配器。 否则,您可以在适配器中创建一个方法来更新数组列表并通知适配器数据集已更改。我希望你能理解这一点。

首先是最简单的

【讨论】:

非常感谢。我明白了,我按照你说的做了。并且成功了。 完美。如果有帮助,请将其标记为答案

以上是关于Recyclerview 适配器错误:Android Studio 中的 Arraylist 大小为零的主要内容,如果未能解决你的问题,请参考以下文章

RecyclerView:没有附加适配器;跳过布局错误

错误:E/RecyclerView:未连接适配器;跳过片段上的布局

错误 ANDROID STUDIO E/RecyclerView:未连接适配器;跳过布局

Recyclerview 适配器错误:Android Studio 中的 Arraylist 大小为零

RecyclerView:没有附加适配器;跳过布局[重复]

Android Java RecyclerView 错误:未连接适配器;跳过布局[重复]