Как я могу показать изображение в Recyclerview — ошибка отображения изображения в Recyclerview

#java #android #android-recyclerview #adapter

Вопрос:

Во-первых, извините, если мое объяснение на английском языке плохое. Моя проблема в том, что я пытаюсь создать приложение погоды и хочу показать прогноз на 5 дней.Я сохраняю данные в arraylist, которые я извлекаю из api и отправляю в свой класс адаптера. Как вы знаете, значки weahter выражаются в виде строки в weather api. например, «010d» — это что-то вроде этого.Я собираюсь показать recyclerview, что я написал прогноз на 5 дней. Все работает, но значки не отображаются. Я делюсь кодами, которые я сделал.

Я получаю данные в классе прогноза Мой класс прогноза

  public class forecast extends AppCompatActivity {

ActivityResultLauncher<String> permissionLauncher;
LocationManager locationManager;
LocationListener locationListener;

ImageView forecast_back_icon;

RecyclerView recyclerviewforecast;
String API_KEY_FORECAST;
String URL_FORECAST;
Double Latitude,Longitude;
ArrayList<RecyclerviewModel> arrayList;
ForecastAdapter forecastAdapter;



 public forecast(){
    super();
 }


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);

    forecast_back_icon();

}



@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);
    init();



}

public void forecast_back_icon(){
    forecast_back_icon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent IntentForecastToMain = new Intent(forecast.this,MainActivity.class);
            startActivity(IntentForecastToMain);
        }
    });
}

public void get_forecast_data(Double Lat, Double Long){

    //EXAMPLE URL
    //https://api.openweathermap.org/data/2.5/weather?lat={lat}amp;lon={lon}amp;appid={API key}
    
    API_KEY_FORECAST = "c29ecfafd4a70caad8fee38d6054bfc7";
    URL_FORECAST = "https://api.openweathermap.org/data/2.5/onecall?lat=" Lat "amp;lon=" Long "amp;exclude=current,minutely,hourly,alertsamp;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();

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

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

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

 }
 

Мой класс адаптера

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

ArrayList<RecyclerviewModel> ForecastArraylist;
ForecastDailyIconConverter forecastDailyIconConverter;


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.txtRecyclerviewDay.setText("day " (position 1));
    holder.binding.txtRecyclerviewTemp.setText("temperature:" temperature.toString().substring(0,4) "°");
    holder.binding.txtRecyclerviewFeelslike.setText("feels like:" feels_like.toString().substring(0,4) "°");
    holder.binding.txtRecyclerviewHumidity.setText("humidity:%" ForecastArraylist.get(position).getHumadity());
    holder.binding.txtRecyclerviewPressure.setText("pressure:" ForecastArraylist.get(position).getPressure() "hPa");
    holder.binding.txtRecyclerviewWindSpeed.setText("wind speed:" ForecastArraylist.get(position).getWind_speed() "km/h");
    holder.binding.txtRecyclerviewCloud.setText(ForecastArraylist.get(position).getDescription());
    String icon_id = ForecastArraylist.get(position).getId();

    forecastDailyIconConverter = new ForecastDailyIconConverter();
    int id1 = forecastDailyIconConverter.ConvertIntoNumeric(icon_id);
    load_weather_icon(id1,holder);


}

public void load_weather_icon(int id1,MyForecastViewHolder holder){

    if(id1>=200 amp;amp; id1 <= 232){
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.thunderstorm);
    }
    else if(id1>=300 amp;amp; id1<= 321){
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
    }
    else if(id1>=500 amp;amp; id1<= 504){
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.rain);
    }
    else if(id1 == 511){
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
    }
    else if(id1>=520 amp;amp; id1<= 531){
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.showerrain);
    }
    else if(id1>=600 amp;amp; id1<= 622){
        holder.binding.recyclerviewCloudImg.setBackgroundResource(R.drawable.snow);
    }
    else if(id1>=701 amp;amp; 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);
    }
}

@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;
    }
}


 }
 

Я пытался писать значки в onbindviewholder без функции load_weather_icon(), и это не сработало

Мой xml recyclerview_row

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100"
android:background="#FA8072"
 
 <LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:orientation="vertical"
    android:padding="5dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_weight="40"
   >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        >
        <TextView
            android:id="@ id/txt_recyclerview_day"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="day:"
            android:textColor="@color/white"
            ></TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        >
        <TextView
            android:id="@ id/txt_recyclerview_temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="temp:"
            android:textColor="@color/white"
            ></TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        >

        <TextView
            android:id="@ id/txt_recyclerview_feelslike"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="feels like:"
            android:textColor="@color/white"></TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <TextView
            android:id="@ id/txt_recyclerview_pressure"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="pressure:"
            android:textColor="@color/white"></TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <TextView
            android:id="@ id/txt_recyclerview_humidity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="humidity:"
            android:textColor="@color/white"></TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <TextView
            android:id="@ id/txt_recyclerview_wind_speed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="wind speed:"
            android:textColor="@color/white"></TextView>
    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="60"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:gravity="right"

    android:orientation="vertical"
    >

    <ImageView
        android:id="@ id/recyclerview_cloud_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        ></ImageView>

   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@ id/txt_recyclerview_cloud"
       android:text=""
       android:gravity="center"
       android:layout_margin="5dp"
       android:padding="5dp"
       android:textColor="@color/white"
       ></TextView>

</LinearLayout>
 

введите описание изображения здесь

Ответ №1:

  • Используйте библиотеку Glide или Picasso
  • Они лучше всего подходят для приложений такого типа

Комментарии:

1. Я собираюсь попробовать. Спасибо. у вас есть другое предложение. как вы думаете, какой из них лучше использовать.

2. я предпочитаю glide lib

3. Извините, это моя вина. Строковые значения поступают из api, например «10d», но я проверял целочисленные значения, такие как 500, 600, в моем классе адаптера if. Я исправил их, и это сработало. Я пробовал скользить, как вы сказали. это также сработало. Спасибо

4. пожалуйста. Рад помочь