android-fragments 如何获得天气图标使用翻新

5f0d552i  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(143)

我无法得到图标和摘要时,点击按钮检查任何位置数据,因为当我点击按钮,我得到湿度压力和温度,但在添加摘要和图标行在主要活动应用程序崩溃,它返回空如何解决它。
下面是按钮点击的主要代码,我正在获取温度和湿度,但在添加这两行获取摘要和图标时,应用程序崩溃,,,,,,,,,,,,,,,下面是主要活动

public class MainActivity extends AppCompatActivity {
    private EditText editText;
     private Button button;
    private TextView responseText;
    ImageView iconImageView;
    TextView summaryTextView;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();}    
 private void init() {
    editText = findViewById(R.id.city_name);
    button = findViewById(R.id.city_click);
    responseText = findViewById(R.id.response_text);
    iconImageView = findViewById(R.id.iconImageView);
    summaryTextView = findViewById(R.id.summaryTextView);
    button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchWeatherDetails();
            }
        });
    }
    private void fetchWeatherDetails() {
        Retrofit retrofit = NetworkClient.getRetrofitClient();
        weatherapis weatherAPIs = retrofit.create(weatherapis.class);
        Call<Weather> call;
        call = weatherAPIs.getWeatherByCity((editText.getText().toString()),"c70504e5e7ee0c5962f9407a45a2e75b");
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Response response, Retrofit retrofit) {
                if (response.body() != null) {
                    Weather wResponse = (Weather) response.body();
                    responseText.setText("Temp: " + wResponse.getMain().getTemp() + "\n " +
                            "Humidity: " + wResponse.getMain().getHumidity() + "\n" +
                            //  "icon:"+ wResponse.getWeather_().getIcon() +"\n"+
                            "Pressure: " + wResponse.getMain().getPressure());
                   summaryTextView.setText(wResponse.getCurrently().getSummary());
                   iconImageView.setImageResource(WeatherIconUtil.ICONS.get(wResponse.getCurrently().getIcon()));
                }}
            @Override
            public void onFailure(Throwable t) {}});
    }

以下是用于获取图标的Weathericonutil类

public final class WeatherIconUtil {
public static final Map<String, Integer> ICONS;
static {
    Map<String, Integer> iconMap = new HashMap<>();
    iconMap.put("clear-day", R.drawable.ic_clear_day);
    iconMap.put("clear-night", R.drawable.ic_clear_night);
    iconMap.put("rain", R.drawable.ic_rain);
    iconMap.put("snow", R.drawable.ic_snow);
    iconMap.put("sleet", R.drawable.ic_sleet);
    iconMap.put("wind", R.drawable.ic_wind);
    iconMap.put("fog", R.drawable.ic_fog);
    iconMap.put("cloudy", R.drawable.ic_cloudy);
    iconMap.put("partly-cloudy-day", R.drawable.ic_partly_cloudy_day);
    iconMap.put("partly-cloudy-night", R.drawable.ic_partly_cloudy_night);
    iconMap.put("thunderstorm", R.drawable.ic_thunderstorm);

    ICONS = Collections.unmodifiableMap(iconMap);
}
}

以下是我的天气api界面

public interface weatherapis {
String api_key = "my key";
String BASE_URL= "http://api.openweathermap.org/data/2.5/";
// static Retrofit retrofit = null;
@GET("/data/2.5/weather")
Call<Weather> getCurrently();

/*
    Get request to fetch city weather.Takes in two parameter-city name and API key.
    */
    @GET("/data/2.5/weather")
    Call<Weather> getWeatherByCity(@Query("q") String city, @Query("appid") String apiKey);

}

当前来自模型的类

public class Currently {

@SerializedName("time")
@Expose
private Integer time;
@SerializedName("summary")
@Expose
private String summary;
@SerializedName("icon")
@Expose
private String icon;
@SerializedName("temperature")
@Expose
private Double temperature;

public Integer getTime() {
    return time;
}

public void setTime(Integer time) {
    this.time = time;
}

public String getSummary() {
    return summary;
}

public void setSummary(String summary) {
    this.summary = summary;
}

public String getIcon() {
    return icon;
}

public void setIcon(String icon) {
    this.icon = icon;
}

public Double getTemperature() {
    return temperature;
}

public void setTemperature(Double temperature) {
    this.temperature = temperature;
}

}

以下网络客户端

public class NetworkClient {

public static final String BASE_URL = "http://api.openweathermap.org";
public static Retrofit retrofit;
/*
This public static method will return Retrofit client
anywhere in the appplication
*/

public static Retrofit getRetrofitClient() {
    //If condition to ensure we don't create multiple retrofit instances in a single application
    if (retrofit == null) {
        //Defining the Retrofit using Builder
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) //This is the only mandatory call on Builder object.
                .addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
                .build();
    }
    return retrofit;
}

}

在主活动中获取摘要和图标时崩溃日志

09-12 15:54:18.648 12336-12336/? D/AndroidRuntime: Shutting down VM
09-12 15:54:18.648 12336-12336/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nv.thisisitman, PID: 12336
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String models.Currently.getSummary()' on a null object reference
    at com.nv.thisisitman.MainActivity$2.onResponse(MainActivity.java:63)
    at retrofit.ExecutorCallAdapterFactory$ExecutorCallback$1.run(ExecutorCallAdapterFactory.java:86)
    at android.os.Handler.handleCallback(Handler.java:754)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6239)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
oo7oh9g9

oo7oh9g91#

请检查来自调试的响应。api响应中没有摘要。
检查以下示例响应:没有总结

{
  "lat": 39.31,
  "lon": -74.5,
  "timezone": "America/New_York",
  "timezone_offset": -18000,
  "current": {
    "dt": 1646318698,
    "sunrise": 1646306882,
    "sunset": 1646347929,
    "temp": 282.21,
    "feels_like": 278.41,
    "pressure": 1014,
    "humidity": 65,
    "dew_point": 275.99,
    "uvi": 2.55,
    "clouds": 40,
    "visibility": 10000,
    "wind_speed": 8.75,
    "wind_deg": 360,
    "wind_gust": 13.89,
    "weather": [
      {
        "id": 802,
        "main": "Clouds",
        "description": "scattered clouds",
        "icon": "03d"
      }
    ]
  },
  "minutely": [
    {
      "dt": 1646318700,
      "precipitation": 0
    },
    ...
  },
    "hourly": [
    {
      "dt": 1646316000,
      "temp": 281.94,
      "feels_like": 278.49,
      "pressure": 1014,
      "humidity": 67,
      "dew_point": 276.16,
      "uvi": 1.49,
      "clouds": 52,
      "visibility": 10000,
      "wind_speed": 7.16,
      "wind_deg": 313,
      "wind_gust": 10.71,
      "weather": [
        {
          "id": 803,
          "main": "Clouds",
          "description": "broken clouds",
          "icon": "04d"
        }
      ],
      "pop": 0.03
    },
    ...
  }
    "daily": [
    {
      "dt": 1646326800,
      "sunrise": 1646306882,
      "sunset": 1646347929,
      "moonrise": 1646309880,
      "moonset": 1646352120,
      "moon_phase": 0.03,
      "temp": {
        "day": 281.63,
        "min": 271.72,
        "max": 282.21,
        "night": 271.72,
        "eve": 277.99,
        "morn": 280.92
      },
      "feels_like": {
        "day": 277.83,
        "night": 264.72,
        "eve": 273.35,
        "morn": 277.66
      },
      "pressure": 1016,
      "humidity": 55,
      "dew_point": 273.12,
      "wind_speed": 9.29,
      "wind_deg": 3,
      "wind_gust": 16.48,
      "weather": [
        {
          "id": 500,
          "main": "Rain",
          "description": "light rain",
          "icon": "10d"
        }
      ],
      "clouds": 49,
      "pop": 0.25,
      "rain": 0.11,
      "uvi": 3.38
    },
    ...
    },
    "alerts": [
    {
      "sender_name": "NWS Philadelphia - Mount Holly (New Jersey, Delaware, Southeastern Pennsylvania)",
      "event": "Small Craft Advisory",
      "start": 1646344800,
      "end": 1646380800,
      "description": "...SMALL CRAFT ADVISORY REMAINS IN EFFECT FROM 5 PM THIS\nAFTERNOON TO 3 AM EST FRIDAY...\n* WHAT...North winds 15 to 20 kt with gusts up to 25 kt and seas\n3 to 5 ft expected.\n* WHERE...Coastal waters from Little Egg Inlet to Great Egg\nInlet NJ out 20 nm, Coastal waters from Great Egg Inlet to\nCape May NJ out 20 nm and Coastal waters from Manasquan Inlet\nto Little Egg Inlet NJ out 20 nm.\n* WHEN...From 5 PM this afternoon to 3 AM EST Friday.\n* IMPACTS...Conditions will be hazardous to small craft.",
      "tags": [

      ]
    },
    ...
  ]

相关问题