繁体   English   中英

Android 上的 OpenWeatherApi 开发失败(?)

[英]OpenWeatherApi on Android Development failing(?)

所以基本上我正在尝试构建一个显示天气(和其他一些东西)的移动应用程序,但我在 API 上遇到了一些问题。

我已经尝试了很长时间,解决了这个问题,但没有任何效果。

每次我运行该应用程序时,它都会显示“无法获取数据”(显然是因为我希望它在失败时打印出来)但我不知道为什么。

package com.example.firsttry

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.google.gson.annotations.SerializedName
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import java.text.DateFormat
import java.util.*

class MainActivity : AppCompatActivity() {
    var timer = Timer()
    lateinit var dateTextView: TextView
    lateinit var timeTextView: TextView
    lateinit var temperatureTextView: TextView
    var temperature:Double = 0.0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dateTextView = findViewById(R.id.xml_text_date)
        timeTextView = findViewById(R.id.xml_text_time)
        temperatureTextView = findViewById(R.id.xml_text_temperature)
        val api = WeatherApi()
        val call = api.getWeather("126a2ec583e6e38a9cbc5e8144c278c7", "New York City")
        call.enqueue(object : Callback<WeatherResponse> {
            override fun onResponse(
                call: Call<WeatherResponse>,
                response: Response<WeatherResponse>
            ) {
                if (response.isSuccessful) {
                    val weather = response.body()
                    val temp = weather?.temperature?.temp
                    if (temp != null) {
                        val temperature = temp - 273.15
                        temperatureTextView.text = temperature.toString() + "°C"
                    } else {
                        temperatureTextView.text = "Temperature Data not available"
                    }
                    // do something with weather data
                } else {
                    temperatureTextView.text = "Error Occurred"// handle error
                }
                response.body().toString()
            }

            override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
                temperatureTextView.text = "Failed to fetch data"
                t.printStackTrace()
                // handle failure
            }
        })
        timer.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                runOnUiThread { updateTime() }
            }
        }, 0, 1000)
    }
    fun updateTime() {
        val calendar = Calendar.getInstance().time
        val dateFormat = DateFormat.getDateInstance(DateFormat.FULL).format(calendar)
        val timeFormat = DateFormat.getTimeInstance().format(calendar)
        dateTextView.text = dateFormat
        timeTextView.text = timeFormat
    }
    override fun onDestroy() {
        super.onDestroy()
        timer.cancel()
    }}
class WeatherResponse {
    @SerializedName("name")
    val cityName: String? = null

    @SerializedName("main")
    val temperature: Temperature? = null
}
class Temperature {
    @SerializedName("temp")
    val temp: Double? = null
}
class WeatherApi {
    private val retrofit = Retrofit.Builder()
        .baseUrl("http://api.openweathermap.org/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    fun getWeather(apiKey: String, city: String): Call<WeatherResponse> {
        val service = retrofit.create(WeatherService::class.java)
        return service.getWeather(apiKey, city)
    }
}
interface WeatherService {
    @GET("data/2.5/weather")
    fun getWeather(
        @Query("appid") apiKey: String,
        @Query("q") city: String
    ): Call<WeatherResponse>
}

谁能找到我做的任何错误?

我修好了它。 我调试了一下,然后检查了错误。 第一件事是我的手机没有 inte.net 连接,第二个问题是 baseurl 是 http:// 而不是 https://

您的基础 URL 应该以 https:// 开头,而不是 http://此处提供的其他信息

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API密钥}

并用应用程序验证这一点

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM