Skip to content

Commit 6d32eed

Browse files
Fix: Fixed error with fetchWeatherData not finding url.
Signed-off-by: HeCodes2Much <wayne6324@gmail.com>
1 parent bdfa980 commit 6d32eed

File tree

2 files changed

+66
-42
lines changed

2 files changed

+66
-42
lines changed

app/src/main/java/com/github/droidworksstudio/launcher/helper/AppHelper.kt

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,9 @@ import com.github.droidworksstudio.launcher.accessibility.ActionService
2626
import com.github.droidworksstudio.launcher.helper.weather.WeatherResponse
2727
import com.github.droidworksstudio.launcher.utils.WeatherApiService
2828
import com.google.gson.Gson
29-
import kotlinx.coroutines.Dispatchers
30-
import kotlinx.coroutines.withContext
3129
import retrofit2.Retrofit
3230
import retrofit2.converter.gson.GsonConverterFactory
31+
import java.net.UnknownHostException
3332
import java.util.Calendar
3433
import java.util.concurrent.TimeUnit
3534
import javax.inject.Inject
@@ -252,43 +251,52 @@ class AppHelper @Inject constructor() {
252251
}
253252
}
254253

255-
suspend fun fetchWeatherData(
254+
sealed class WeatherResult {
255+
data class Success(val weatherResponse: WeatherResponse) : WeatherResult()
256+
data class Failure(val errorMessage: String) : WeatherResult()
257+
}
258+
259+
fun fetchWeatherData(
256260
context: Context,
257261
latitude: Float,
258262
longitude: Float
259-
): WeatherResponse {
263+
): WeatherResult {
260264
// Check if cached data is available and not expired
261265
val cachedWeatherData = context.getWeatherDataFromCache()
262266
if (cachedWeatherData?.let { System.currentTimeMillis() - it.timestamp < TimeUnit.MINUTES.toMillis(15) } == true) {
263-
return cachedWeatherData.weatherResponse
267+
return WeatherResult.Success(cachedWeatherData.weatherResponse)
264268
}
265269

266-
267270
// Fetch weather data from the network
268271
val apiKey = BuildConfig.API_KEY
272+
val baseURL = "api.openweathermap.org"
269273
val units = "metric"
270274

271-
val retrofit = Retrofit.Builder()
272-
.baseUrl("https://api.openweathermap.org/data/2.5/")
273-
.addConverterFactory(GsonConverterFactory.create())
274-
.build()
275+
try {
276+
val retrofit = Retrofit.Builder()
277+
.baseUrl("https://$baseURL/data/2.5/")
278+
.addConverterFactory(GsonConverterFactory.create())
279+
.build()
275280

276-
val service = retrofit.create(WeatherApiService::class.java)
281+
val service = retrofit.create(WeatherApiService::class.java)
277282

278-
return withContext(Dispatchers.IO) {
279283
val response = service.getWeather("$latitude", "$longitude", units, apiKey).execute()
280284
if (response.isSuccessful) {
281285
val weatherResponse = response.body()
282286
if (weatherResponse != null) {
283287
// Cache the fetched weather data
284288
context.cacheWeatherData(weatherResponse)
285-
weatherResponse
289+
return WeatherResult.Success(weatherResponse)
286290
} else {
287-
throw NullPointerException("Weather response body is null")
291+
return WeatherResult.Failure("Weather response body is null")
288292
}
289293
} else {
290-
throw Exception("Failed to fetch weather data: ${response.errorBody()}")
294+
return WeatherResult.Failure("Failed to fetch weather data: ${response.errorBody()}")
291295
}
296+
} catch (e: UnknownHostException) {
297+
return WeatherResult.Failure("Unknown Host : $baseURL")
298+
} catch (e: Exception) {
299+
return WeatherResult.Failure("${e.message}")
292300
}
293301
}
294302

app/src/main/java/com/github/droidworksstudio/launcher/ui/widgets/WidgetFragment.kt

Lines changed: 43 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import androidx.navigation.fragment.findNavController
2828
import com.github.droidworksstudio.common.capitalizeEachWord
2929
import com.github.droidworksstudio.common.hasInternetPermission
3030
import com.github.droidworksstudio.common.hideKeyboard
31+
import com.github.droidworksstudio.common.showLongToast
3132
import com.github.droidworksstudio.launcher.R
3233
import com.github.droidworksstudio.launcher.databinding.FragmentWidgetsBinding
3334
import com.github.droidworksstudio.launcher.helper.AppHelper
@@ -36,7 +37,9 @@ import com.github.droidworksstudio.launcher.listener.OnSwipeTouchListener
3637
import com.github.droidworksstudio.launcher.listener.ScrollEventListener
3738
import com.github.droidworksstudio.launcher.utils.Constants
3839
import dagger.hilt.android.AndroidEntryPoint
40+
import kotlinx.coroutines.DelicateCoroutinesApi
3941
import kotlinx.coroutines.Dispatchers
42+
import kotlinx.coroutines.GlobalScope
4043
import kotlinx.coroutines.async
4144
import kotlinx.coroutines.launch
4245
import kotlinx.coroutines.withContext
@@ -120,6 +123,7 @@ class WidgetFragment : Fragment(),
120123

121124
}
122125

126+
@OptIn(DelicateCoroutinesApi::class)
123127
private fun setupWeatherWidget() {
124128
val sharedPreferences =
125129
context.getSharedPreferences(Constants.WEATHER_PREFS, Context.MODE_PRIVATE)
@@ -139,7 +143,9 @@ class WidgetFragment : Fragment(),
139143
if (!showWeatherWidget || !context.hasInternetPermission()) return@launch
140144

141145
try {
142-
val weatherDeferred = async { appHelper.fetchWeatherData(context, latitude, longitude) }
146+
val weatherDeferred = GlobalScope.async {
147+
appHelper.fetchWeatherData(context, latitude, longitude)
148+
}
143149

144150
// Prepare UI elements concurrently
145151
withContext(Dispatchers.Main) {
@@ -163,40 +169,50 @@ class WidgetFragment : Fragment(),
163169
}
164170
}
165171

166-
val weatherResponse = weatherDeferred.await()
167-
Log.d("weatherResponse", "$weatherResponse")
172+
val result = weatherDeferred.await()
173+
Log.d("weatherResponse", "$result")
168174

169-
withContext(Dispatchers.Main) {
170-
val timestamp = convertTimestampToReadableDate(weatherResponse.dt)
171-
binding.apply {
172-
weatherCity.text = getString(R.string.widget_weather_location, weatherResponse.name, weatherResponse.sys.country)
173-
weatherTemperature.text = getString(R.string.widget_weather_temp, weatherResponse.main.temp, temperatureScale)
174-
weatherDescription.text = getString(R.string.widget_weather_description, weatherResponse.weather[0].description).capitalizeEachWord()
175-
weatherWind.text = getString(R.string.widget_weather_wind, weatherResponse.wind.speed, speedScale)
176-
weatherHumidity.text = getString(R.string.widget_weather_humidity, weatherResponse.main.humidity)
177-
weatherLastRun.text = timestamp
178-
weatherRefresh.text = getString(R.string.widget_weather_refresh, getString(R.string.refresh_icon))
175+
when (result) {
176+
is AppHelper.WeatherResult.Success -> {
177+
val weatherResponse = result.weatherResponse
179178

180-
val weatherIconBitmap = createWeatherIcon(context, setWeatherIcon(context, weatherResponse.weather[0].id))
181-
weatherIcon.setImageBitmap(weatherIconBitmap) // Ensure this matches your ImageView ID
182-
weatherIcon.setColorFilter(widgetTextColor)
179+
withContext(Dispatchers.Main) {
180+
val timestamp = convertTimestampToReadableDate(weatherResponse.dt)
181+
binding.apply {
182+
weatherCity.text = getString(R.string.widget_weather_location, weatherResponse.name, weatherResponse.sys.country)
183+
weatherTemperature.text = getString(R.string.widget_weather_temp, weatherResponse.main.temp, temperatureScale)
184+
weatherDescription.text = getString(R.string.widget_weather_description, weatherResponse.weather[0].description).capitalizeEachWord()
185+
weatherWind.text = getString(R.string.widget_weather_wind, weatherResponse.wind.speed, speedScale)
186+
weatherHumidity.text = getString(R.string.widget_weather_humidity, weatherResponse.main.humidity)
187+
weatherLastRun.text = timestamp
188+
weatherRefresh.text = getString(R.string.widget_weather_refresh, getString(R.string.refresh_icon))
183189

184-
val sunriseIconBitmap = createSunIcon(context, getString(R.string.sunrise_icon))
185-
sunriseIcon.setImageBitmap(sunriseIconBitmap)
186-
sunriseIcon.setColorFilter(widgetTextColor)
190+
val weatherIconBitmap = createWeatherIcon(context, setWeatherIcon(context, weatherResponse.weather[0].id))
191+
weatherIcon.setImageBitmap(weatherIconBitmap) // Ensure this matches your ImageView ID
192+
weatherIcon.setColorFilter(widgetTextColor)
187193

188-
val sunsetIconBitmap = createSunIcon(context, getString(R.string.sunset_icon))
189-
sunsetIcon.setImageBitmap(sunsetIconBitmap)
190-
sunsetIcon.setColorFilter(widgetTextColor)
194+
val sunriseIconBitmap = createSunIcon(context, getString(R.string.sunrise_icon))
195+
sunriseIcon.setImageBitmap(sunriseIconBitmap)
196+
sunriseIcon.setColorFilter(widgetTextColor)
191197

192-
val sunriseTime = convertTimestampToReadableDate(weatherResponse.sys.sunrise)
193-
sunriseText.text = getString(R.string.widget_sunrise_time, sunriseTime)
198+
val sunsetIconBitmap = createSunIcon(context, getString(R.string.sunset_icon))
199+
sunsetIcon.setImageBitmap(sunsetIconBitmap)
200+
sunsetIcon.setColorFilter(widgetTextColor)
194201

195-
val sunsetTime = convertTimestampToReadableDate(weatherResponse.sys.sunset)
196-
sunsetText.text = getString(R.string.widget_sunset_time, sunsetTime)
202+
val sunriseTime = convertTimestampToReadableDate(weatherResponse.sys.sunrise)
203+
sunriseText.text = getString(R.string.widget_sunrise_time, sunriseTime)
197204

205+
val sunsetTime = convertTimestampToReadableDate(weatherResponse.sys.sunset)
206+
sunsetText.text = getString(R.string.widget_sunset_time, sunsetTime)
207+
208+
weatherRoot.visibility = View.VISIBLE
209+
}
210+
}
211+
}
198212

199-
weatherRoot.visibility = View.VISIBLE
213+
is AppHelper.WeatherResult.Failure -> {
214+
val errorMessage = result.errorMessage
215+
context.showLongToast(errorMessage)
200216
}
201217
}
202218
} catch (e: Exception) {

0 commit comments

Comments
 (0)