Weather location added to SharedPreferences

This commit is contained in:
ottoptj 2024-07-04 02:06:06 +03:00
commit 703eab30ed
3 changed files with 49 additions and 21 deletions

View file

@ -144,6 +144,7 @@ class MainActivity : AppCompatActivity(), AppMenuAdapter.OnItemClickListener, Ap
// Detect swipe up // Detect swipe up
if (deltaY < -swipeThreshold && abs(velocityY) > swipeVelocityThreshold) { if (deltaY < -swipeThreshold && abs(velocityY) > swipeVelocityThreshold) {
openAppMenuActivity() openAppMenuActivity()
weatherSystem.getTemp(this@MainActivity)
} }
// Detect swipe down // Detect swipe down

View file

@ -60,4 +60,16 @@ class SharedPreferenceManager {
editor.apply() editor.apply()
} }
fun setWeatherLocation(cont: Context, location: String) {
val editor = cont.getSharedPreferences("weather_location", AppCompatActivity.MODE_PRIVATE).edit()
val key = "location"
editor.putString(key, location)
editor.apply()
}
fun getWeatherLocation(cont: Context) : String? {
val sharedPreferences = cont.getSharedPreferences("weather_location", AppCompatActivity.MODE_PRIVATE)
val key = "location"
return sharedPreferences.getString(key, null)
}
} }

View file

@ -9,11 +9,13 @@ import android.location.Location
import android.location.LocationListener import android.location.LocationListener
import android.location.LocationManager import android.location.LocationManager
import android.os.Bundle import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject import org.json.JSONObject
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.URL import java.net.URL
@ -21,16 +23,14 @@ import java.util.function.Consumer
class WeatherSystem { class WeatherSystem {
fun getWeather() { private val sharedPreferenceManager = SharedPreferenceManager()
getTempForLocation("latitude=60.16&longitude=24.93")
}
fun getWeatherForCurrentLocation(activity: Activity) { fun getWeatherForCurrentLocation(activity: Activity) {
val locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager val locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locationListener = object : LocationListener { val locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) { override fun onLocationChanged(location: Location) {
println(location) println("Location obtained")
locationManager.removeUpdates(this) locationManager.removeUpdates(this)
} }
@ -39,44 +39,59 @@ class WeatherSystem {
override fun onProviderDisabled(provider: String) {} override fun onProviderDisabled(provider: String) {}
} }
// Check for location permissions
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Permissions are not granted ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
1
)
return return
} }
// Request location updates from both providers
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0f, locationListener) locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0f, locationListener)
// Try to get the last known location from both providers as a fallback
val currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) val currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if (currentLocation != null) { if (currentLocation != null) {
getTempForLocation("latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}") sharedPreferenceManager.setWeatherLocation(activity, "latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}")
}
else {
Toast.makeText(activity, "Unable to get location", Toast.LENGTH_SHORT).show()
} }
} }
private fun getTempForLocation(location: String) { fun getTemp(context: Context) {
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
val url = URL("https://api.open-meteo.com/v1/forecast?$location&current=temperature_2m") val location = sharedPreferenceManager.getWeatherLocation(context)
with(url.openConnection() as HttpURLConnection) { if (location != null) {
requestMethod = "GET" val url = URL("https://api.open-meteo.com/v1/forecast?$location&current=temperature_2m")
with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET"
inputStream.bufferedReader().use { inputStream.bufferedReader().use {
val response = it.readText() val response = it.readText()
val jsonObject = JSONObject(response) val jsonObject = JSONObject(response)
val currentData = jsonObject.getJSONObject("current") val currentData = jsonObject.getJSONObject("current")
val currentWeather = currentData.getInt("temperature_2m") val currentWeather = currentData.getInt("temperature_2m")
println("Field1: $currentWeather") println("Field1: $currentWeather")
}
} }
}} }
else {
withContext(Dispatchers.Main) {
Toast.makeText(context, "No weather location set", Toast.LENGTH_SHORT).show()
}
}
}
} }
} }