Данные о температуре не отображаются в приложении «Погода»JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Данные о температуре не отображаются в приложении «Погода»

Сообщение Anonymous »

Я создаю приложение погоды, используя этот API:

Код: Выделить всё

Url: "https://weatherapi-com.p.rapidapi.com/forecast.json?q=London&days=3"
Header: "X-RapidAPI-Key", "REDACTED"
Header: "X-RapidAPI-Host", "weatherapi-com.p.rapidapi.com" but my weather temperture are showing 0.0 celcius pleae resolve my issue
Это мой XML-код: Это мой код WeatherResponse:

Код: Выделить всё

package com.example.retrofitweatherapi.WeatherData;

import java.util.List;

public class WeatherResponse {

private Location location;
private Current current;
private Forecast forecast;

// Getters and Setters
public Location getLocation() {
return location;
}

public void setLocation(Location location) {
this.location = location;
}

public Current getCurrent() {
return current;
}

public void setCurrent(Current current) {
this.current = current;
}

public Forecast getForecast() {
return forecast;
}

public void setForecast(Forecast forecast) {
this.forecast = forecast;
}

// Inner Classes
public static class Location {
private String name;
private String localtime;
private String region;
private String country;

// Getters and Setters
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getLocaltime() {
return localtime;
}

public void setLocaltime(String localtime) {
this.localtime = localtime;
}

public String getRegion() {
return region;
}

public void setRegion(String region) {
this.region = region;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}
}

public static class Current {
private double tempC;
private Condition condition;
private double humidity;
private double windKph;
private double chancesofRain;

// Getters and Setters
public double getTempC() {
return tempC;
}

public void setTempC(double tempC) {
this.tempC = tempC;
}

public Condition getCondition() {
return condition;
}

public void setCondition(Condition condition) {
this.condition = condition;
}

public double getHumidity() {
return humidity;
}

public void setHumidity(double humidity) {
this.humidity = humidity;
}

public double getWindKph() {
return windKph;
}

public void setWindKph(double windKph) {
this.windKph = windKph;
}

public double getChancesofRain() {
return chancesofRain;
}

public void setChancesofRain(double chancesofRain) {
this.chancesofRain = chancesofRain;
}
}

public static class Condition {
private String text;
private String icon;

// Getters and Setters
public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

public String getIcon() {
return icon;
}

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

public static class Forecast {
private List forecastday;

// Getters and Setters
public List getForecastday() {
return forecastday;
}

public void setForecastday(List forecastday) {
this.forecastday = forecastday;
}
}

public static class ForecastDay {
private String date;
private List hour;
private String forecastDay;

// Getters and Setters
public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public List getHour() {
return hour;
}

public void setHour(List  hour) {
this.hour = hour;
}

public String getForecastDay() {
return forecastDay;
}

public void setForecastDay(String forecastDay) {
this.forecastDay = forecastDay;
}
}

public static class Hour {
private String time;
private double tempC;
private Condition condition;

// Getters and Setters
public String getTime() {
return time;
}

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

public double getTempC() {
return tempC;
}

public void setTempC(double tempC) {
this.tempC = tempC;
}

public Condition getCondition() {
return condition;
}

public void setCondition(Condition condition) {
this.condition = condition;
}
}
}
Это мой класс WeatherInterface:

Код: Выделить всё

package com.example.retrofitweatherapi.WeatherData;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Query;

public interface Weatherinterface
{
@GET("forecast.json")
CallgetWeatherData(
@Header("X-RapidAPI-Key") String api_key,
@Header("X-RapidAPI-Host") String apiHost,
@Query("q") String location,
@Query("days") int days
);
}
Это мой ApiClient:

Код: Выделить всё

package com.example.retrofitweatherapi.WeatherData;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient
{
private static final String BASE_URL="https://weatherapi-com.p.rapidapi.com/";

private static Retrofit retrofit;

public static Retrofit getRetrofitInstance(){
if (retrofit==null){
retrofit=new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Это мой код MainActivity.java:

Код: Выделить всё

package com.example.retrofitweatherapi;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.retrofitweatherapi.WeatherData.ApiClient;
import com.example.retrofitweatherapi.WeatherData.HourModel;
import com.example.retrofitweatherapi.WeatherData.HourlyWeatherAdapter;
import com.example.retrofitweatherapi.WeatherData.WeatherResponse;
import com.example.retrofitweatherapi.WeatherData.Weatherinterface;
import com.example.retrofitweatherapi.databinding.ActivityMainBinding;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

ActivityMainBinding binding;
//1caea1f23fmsh7b6dcc08a73f460p1be99bjsnbe0dc6d81ffa
Weatherinterface weatherinterface;
private static final String API_KEY = "1caea1f23fmsh7b6dcc08a73f460p1be99bjsnbe0dc6d81ffa";
private static final String API_HOST = "weatherapi-com.p.rapidapi.com";
private HourlyWeatherAdapter adapter;
private Listhourlist;
@Override
protected void onCreate(Bundle savedInstanceState)  {
super.onCreate(savedInstanceState);
binding=ActivityMainBinding.inflate(getLayoutInflater());
View view=binding.getRoot();
setContentView(view);

weatherinterface= ApiClient.getRetrofitInstance().create(Weatherinterface.class);

hourlist=new ArrayList();

adapter=new HourlyWeatherAdapter(getApplicationContext(),hourlist);
binding.recyclerviewHourly.setAdapter(adapter);
binding.recyclerviewHourly.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));

fetchWeatherData("London",3);

}

private void fetchWeatherData(String location,int days)
{
Callcall=weatherinterface.getWeatherData(API_KEY,API_HOST,location,days);

call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()&&response.body()!=null){
WeatherResponse weatherResponse=response.body();
UpdateUI(weatherResponse);
}
else
{
Toast.makeText(MainActivity.this, "Failed to fetch weather data", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(MainActivity.this, "No Internet", Toast.LENGTH_SHORT).show();
}
});
}
private void UpdateUI(WeatherResponse weatherResponse){
WeatherResponse.Current current=weatherResponse.getCurrent();
WeatherResponse.Condition condition=current.getCondition();

binding.locationTxt.setText(weatherResponse.getLocation().getName());
binding.txtDate.setText(weatherResponse.getLocation().getLocaltime());
binding.txtTempeture.setText(String.format("%.1f°C",weatherResponse.getCurrent().getTempC()));
binding.ConditionText.setText(condition.getText());
Picasso.get().load("https:" + condition.getIcon());

binding.txtRainChance.setText(String.format("%.0f%%",current.getChancesofRain()));
binding.txtHumidityChance.setText(String.format("%.0f%%",current.getHumidity()));
binding.txtWindyChance.setText(String.format("%.0f km/h",current.getWindKph()));

// Clear and update the hourly weather data
hourlist.clear();

for (WeatherResponse.Hour hour:weatherResponse.getForecast().getForecastday().get(0).getHour()){
String time=hour.getTime().split(" ")[1];
String temp=String.format("%.1f°C",hour.getTempC());
String imageurl= "https:"+hour.getCondition().getIcon();
hourlist.add(new HourModel(time,temp,imageurl));
}
adapter.notifyDataSetChanged();
}
}
При всем этом данные о температуре по-прежнему не отображаются. Что я могу сделать, чтобы это исправить?


Подробнее здесь: https://stackoverflow.com/questions/789 ... eather-app
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»