Home > database >  OpenWeatherApi on Android Development failing(?)
OpenWeatherApi on Android Development failing(?)

Time:01-26

So basically I am trying to build a mobile app, that displays the weather (and some other things), but I have some problems with the API.

I've tried for very long, fixing this, but nothing works.

Everytime I run the app it says "Failed to fetch data" (obviously because I wanted it to print that when it fails) but I don't know why.

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

Can anyone find any errors I did?

CodePudding user response:

I fixed it. I debugged it and then checked the error. First thing was that my phone had no internet connection and the second problem was that the baseurl was http:// and not https://

CodePudding user response:

Your base URL should start with https:// not with http:// additional information available here

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

and verify this with app

  • Related