如何将 Openweathermap 图标代码转换为实际图像

How to convert Openweathermap icon code to actual image

我需要帮助将 OpenWeatherMap 图标转换为实际的 png 图像。

到目前为止,我已将图标代码 (iconName) 检索到文本视图中,并为完整图像创建了字符串 url (iconUrl)。

String iconName = JSONWeather.getString("icon");
String iconUrl = JSONWeather.getString(IMG_URL + iconName +".png");

但是我很难将这个 url 插入到图像视图中。

我收到的错误是

E/Utils:解析地震 JSON 结果时出现问题 org.json.JSONException:https://openweathermap.org/img/w/04n.png

没有值

我看到 Picasso 可以在这里使用,但下面的代码显示 viewHolder 为红色,我不知道需要添加什么来解决这个问题。

Picasso.with(viewHolder.itemView.getContext()).load(iconUrl).into(viewHolder.condIcon)



<ImageView
        android:id="@+id/condIcon"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
       />


   ImageView iconView =  findViewById(R.id.condIcon);
        iconView.setImageURI(Uri.parse(earthquake.iconUrl));

解决了! 值得一提的是,我的应用程序包含 3 个 classes:Utils、MainActivity 和 Event。

首先,在Utils.java 解析你的JSON图标:

 /**URL for the icons location at OpenWeatherMap*/
    public static final String IMG_URL = "https://openweathermap.org/img/w/";

 //Retrieve icon code from website
                String iconName = JSONWeather.getString("icon");

其次,在活动中。 java 添加:

在顶部

public final String iconName;

和class

 public Event(.....String eventIconName)
{ .......
     iconName=eventIconName;
      }

第三,在MainActivity.java 添加图像视图和毕加索参考:

//Convert icon code from the OpenWeatherMap website into the image and insert into the ImageView. Path consists of URL declared in Utils.java, and @param iconName, declared in Event.java.
// JSON parser method used in Utils.java class retrieves icon code from OpenWeatherMap (iconName), .png extension is added.

    ImageView iconView =  findViewById(R.id.condIcon);
    Picasso.with(this).load(IMG_URL + weather.iconName +".png").into(iconView);

坦率地说,我花了 2 天时间弄明白了。希望这对其他人有所帮助。