content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.wheatherapp.data.local.cashRoom import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.espresso.matcher.ViewMatchers.assertThat import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.example.wheatherapp.data.local.DataBase import com.example.wheatherapp.data.models.WeatherResponse import com.google.android.gms.tasks.Task import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runBlockingTest import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.nullValue import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlinx.coroutines.flow.first @SmallTest // organization process and we choose smallest bec it across unit we not have two or more class integrated with each other @RunWith(AndroidJUnit4::class) // can not use it bec it placed by default class CashDaoTest{ lateinit var dataBase: DataBase lateinit var dao: CashDao @get:Rule //work synchronize (on the same thread) var instantTaskExecutorRule = InstantTaskExecutorRule() @Before // the process that did before as initialize object fun SetUp(){ dataBase = Room.inMemoryDatabaseBuilder( getApplicationContext(), DataBase::class.java ).build() dao = dataBase.favouriteDao() } @After // the process that did after as close database fun tearDown(){ dataBase.close() } val weatherSuccessResponse = WeatherResponse( city = null, cnt = null, cod = null, list = emptyList(), message = null ) @Test fun getFavourites_favouritesById000_theSameFavorite() = runBlockingTest { //Given val favorite = CashEntity(id = 1, weather = weatherSuccessResponse) dao.insertFavourites(favorite) //When val resultList = dao.getFavourites().first() //Then assertThat(resultList, not(nullValue())) assertThat(resultList.size, `is`(1)) assertThat(resultList[0], `is`(favorite)) } }
WeatherForecastApp/app/src/androidTest/java/com/example/wheatherapp/data/local/cashRoom/CashDaoTest.kt
2905908381
package com.example.wheatherapp.data.local.favourite import com.example.wheatherapp.data.local.cashRoom.CashDao import com.example.wheatherapp.data.local.cashRoom.CashEntity import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.espresso.matcher.ViewMatchers.assertThat import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.example.wheatherapp.data.local.DataBase import com.example.wheatherapp.data.models.WeatherResponse import com.google.android.gms.tasks.Task import junit.framework.TestCase.assertNotNull import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runBlockingTest import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.nullValue import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest @SmallTest // organization process and we choose smallest bec it across unit we not have two or more class integrated with each other @RunWith(AndroidJUnit4::class) // can not use it bec it placed by default class MyFavouritesDaoTest { lateinit var dataBase: DataBase lateinit var dao: MyFavouritesDao @get:Rule //work synchronize (on the same thread) var instantTaskExecutorRule = InstantTaskExecutorRule() @Before // the process that did before as initialize object fun SetUp() { dataBase = Room.inMemoryDatabaseBuilder( getApplicationContext(), DataBase::class.java ).build() dao = dataBase.myfavDao() } @After // the process that did after as close database fun tearDown() { dataBase.close() } @Test fun getFavourites_returnNull() = runBlockingTest { //When val resultList = dao.getFavorites().first() //Then assertNotNull(resultList) assertThat(resultList, `is`(emptyList())) } @Test fun getFavourites_favouritesById000_theSameFavorite() = runTest { //Given val favorite = MyFavouriteEntity(1, "", 0.0, 0.0) dao.insertFavorite(favorite) //When val resultList = dao.getFavorites().first() //Then assertThat(resultList, not(nullValue())) assertThat(resultList.size, `is`(1)) assertThat(resultList.get(0).id, `is`(1)) assertThat(resultList.get(0).city, `is`("")) assertThat(resultList.get(0).latitude, `is`(0.0)) assertThat(resultList.get(0).longitude, `is`(0.0)) } @Test fun deleteFavorite_deleteById_thesameFavourite()= runBlockingTest { //Given val favorite = MyFavouriteEntity(1, "", 0.0, 0.0) dao.insertFavorite(favorite) dao.deleteFavorite(favorite) //when val resultList = dao.getFavorites().first() //Then assertNotNull(resultList) assertThat(resultList, `is`(emptyList())) } }
WeatherForecastApp/app/src/androidTest/java/com/example/wheatherapp/data/local/favourite/MyFavouritesDaoTest.kt
2660424909
package com.example.wheatherapp.data.local import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.espresso.matcher.ViewMatchers import androidx.test.filters.MediumTest import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.models.City import com.example.wheatherapp.data.models.Coord import com.example.wheatherapp.data.models.WeatherResponse import junit.framework.TestCase import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.runTest import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.manipulation.Ordering.Context @MediumTest // integration test (test two classes ) class LocalDatabaseImpTest{ lateinit var dataBase: DataBase lateinit var localDatabaseImp : LocalDatabaseImp @Before // the process that did before as initialize object fun SetUp(){ dataBase = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), DataBase::class.java ).allowMainThreadQueries() .build() localDatabaseImp = LocalDatabaseImp(getApplicationContext()) } @After // the process that did after as close database fun tearDown(){ dataBase.close() } @Test fun getNetWork_networkName_theSameTasknserted()= runBlockingTest { //Given val newCashEntity = CashEntity( id = null, weather = WeatherResponse() // Provide the necessary parameters. ) localDatabaseImp.insertNetWork(newCashEntity) } @Test fun getFavourites_returnNull() = runTest { //When val resultList = localDatabaseImp.getFavourites().first() //Then TestCase.assertNotNull(resultList) assertThat(resultList, CoreMatchers.`is`(emptyList())) } @Test fun getMyFavourite_favouritesById000_theSameFavorite() = runTest { //Given val favorite = MyFavouriteEntity(1, "", 0.0, 0.0) localDatabaseImp.insertLocation(favorite) //When val resultList = localDatabaseImp.getFavourites().first() //Then ViewMatchers.assertThat(resultList, CoreMatchers.not(CoreMatchers.nullValue())) ViewMatchers.assertThat(resultList.size, CoreMatchers.`is`(1)) ViewMatchers.assertThat(resultList.get(0).id, CoreMatchers.`is`(1)) ViewMatchers.assertThat(resultList.get(0).city, CoreMatchers.`is`("")) ViewMatchers.assertThat(resultList.get(0).latitude, CoreMatchers.`is`(0.0)) ViewMatchers.assertThat(resultList.get(0).longitude, CoreMatchers.`is`(0.0)) } @Test fun deleteFavorite_deleteById_thesameFavourite()= runTest { //Given val favorite = MyFavouriteEntity(1, "", 0.0, 0.0) localDatabaseImp.insertLocation(favorite) localDatabaseImp.deleteFavourite(favorite) //when val resultList = localDatabaseImp.getFavourites().first() //Then TestCase.assertNotNull(resultList) assertThat(resultList, CoreMatchers.`is`(emptyList())) } @Test fun getNetwork_createApiObject_thesameFavourite()= runTest { //Given val favorite = CashEntity(1, WeatherResponse(City(Coord(0.0,0.0),"",0,"",0,0,0,0),0,"0", emptyList(),0)) localDatabaseImp.insertNetWork(favorite) //when val resultList = localDatabaseImp.getNetwork().first() //Then TestCase.assertNotNull(resultList) assertThat(resultList.get(0), `is`(favorite)) } @Test fun getNetwork_createApiObjectThenDelete_returnEmptyList()= runTest { //when val resultList = localDatabaseImp.getNetwork().first() //Then TestCase.assertNotNull(resultList) assertThat(resultList.size, `is`(0)) } }
WeatherForecastApp/app/src/androidTest/java/com/example/wheatherapp/data/local/LocalDatabaseImpTest.kt
2001494057
package com.example.wheatherapp.ui.favourite.viewmodel import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.wheatherapp.data.Repository.FakeRepositoryTest import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.state.HomeResponseState import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.test.runBlockingTest import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert import org.hamcrest.MatcherAssert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class FavouriteViewModelTest{ lateinit var repo: FakeRepositoryTest lateinit var viewModel: FavouriteViewModel @get:Rule val rule = InstantTaskExecutorRule() @Before fun setUp() { repo = FakeRepositoryTest() viewModel = FavouriteViewModel(repo) } @Test fun getFvourit_returnEmptyList()= runBlockingTest { viewModel.getFavouriteList() val task= launch { viewModel.favouriteList.collect { when (it) { is HomeResponseState.OnSuccess -> { assertThat(it.data.size, `is`(0)) } else -> {} } } } task.cancel() } @Test fun getFourite_AddFav_returnIt()= runBlockingTest { //give var fav = MyFavouriteEntity(1,"test",0.0,0.0) //when repo.insertFavourites(fav) viewModel.getFavouriteList() val task= launch { viewModel.favouriteList.collect { when (it) { is HomeResponseState.OnSuccess -> { //assert assertThat(it.data.size, `is`(1)) assertThat(it.data.get(0).city, `is`("test")) assertThat(it.data.get(0).latitude, `is`(0.0)) assertThat(it.data.get(0).longitude, `is`(0.0)) } else -> {} } } } task.cancel() } @Test fun getFourite_AddFavThenDelete_returnNull()= runBlockingTest { //give var fav = MyFavouriteEntity(1,"test",0.0,0.0) //when repo.insertFavourites(fav) viewModel.deleteFavourite(fav) viewModel.getFavouriteList() val task= launch { viewModel.favouriteList.collect { when (it) { is HomeResponseState.OnSuccess -> { //assert assertThat(it.data.size, `is`(0)) } else -> {} } } } task.cancel() } }
WeatherForecastApp/app/src/test/java/com/example/wheatherapp/ui/favourite/viewmodel/FavouriteViewModelTest.kt
912456166
package com.example.wheatherapp import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
WeatherForecastApp/app/src/test/java/com/example/wheatherapp/ExampleUnitTest.kt
763295074
package com.example.wheatherapp.data.Repository import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.wheatherapp.data.local.FakeLocalDatabaseTest import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.models.City import com.example.wheatherapp.data.models.Coord import com.example.wheatherapp.data.models.WeatherResponse import com.example.wheatherapp.data.remote.FakeRemoteDataSourceTest import junit.framework.TestCase.assertNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.runTest import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test class RepositoryTest { import org.junit.Before import org.junit.Rule class RepositoryTest{ @get:Rule val rule = InstantTaskExecutorRule() private lateinit var fakeLocal: FakeLocalDatabaseTest private lateinit var fakeRemote: FakeRemoteDataSourceTest private lateinit var repository: Repository val weatherResponse = WeatherResponse(City(Coord(0.0, 0.0), "", 0, "", 0, 0, 0, 0), 0, "0", emptyList(), 0) @Before fun setUp() { fakeLocal = FakeLocalDatabaseTest() fakeRemote = FakeRemoteDataSourceTest() repository = Repository(fakeRemote, fakeLocal) } @Test fun getWeatherDetails_returnWeatherTheCountryAlex() = runBlockingTest { //then val result = repository.getWeatherDetails(0.0, 0.0, "", "").first() //assert result assertNotNull(result) assertThat(result.city?.country, `is` ("Alex")) } @Test fun getFavourites_returnEmptyList() = runBlockingTest { //When val resultList = repository.getFavourites().first() //Then assertNotNull(resultList) assertThat(resultList, `is`(emptyList())) } @Test fun getFavourites_favouritesById000_theSameFavorite() = runTest { //Given val favorite = MyFavouriteEntity(1, "", 0.0, 0.0) repository.insertFavourites(favorite) //When val resultList = repository.getFavourites().first() //Then assertThat(resultList, CoreMatchers.not(CoreMatchers.nullValue())) assertThat(resultList.size, `is`(1)) assertThat(resultList.get(0).id, `is`(1)) assertThat(resultList.get(0).city, `is`("")) assertThat(resultList.get(0).latitude, `is`(0.0)) assertThat(resultList.get(0).longitude, `is`(0.0)) } @Test fun deleteFavorite_deleteById_thesameFavourite()= runBlockingTest { //Given val favorite = MyFavouriteEntity(1, "", 0.0, 0.0) repository.insertFavourites(favorite) repository.deleteFavourite(favorite) //when val resultList = repository.getFavourites().first() //Then assertNotNull(resultList) assertThat(resultList, `is`(emptyList())) } @Test fun getLastWeatherDetails_returnZero() = runBlockingTest { //then val result = repository.getLastSavedWeather().first() //assert result assertNotNull(result) assertThat(result.size, `is` (0)) } }
WeatherForecastApp/app/src/test/java/com/example/wheatherapp/data/Repository/RepositoryTest.kt
666777142
package com.example.wheatherapp.data.Repository import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cash.Temperature import com.example.wheatherapp.data.local.cash.WindSpeed import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.models.WeatherResponse import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class FakeRepositoryTest( private val locations: MutableList<MyFavouriteEntity>? = mutableListOf(), private val api: MutableList<CashEntity>? = mutableListOf(), ) : IRepository { override fun getFavourites(): Flow<List<MyFavouriteEntity>> { return flow { val location = locations?.toList() if (location.isNullOrEmpty()) { emit(emptyList()) } else { emit(location) } } } override suspend fun insertFavourites(favourite: MyFavouriteEntity) { locations?.add(favourite) } override suspend fun deleteFavourite(favourite: MyFavouriteEntity) { locations?.remove(favourite) } override suspend fun getWeatherDetails( latitude: Double, longitude: Double, units: String, language: String ): Flow<WeatherResponse> { TODO("Not yet implemented") } override suspend fun getWeatherDetailsForAlert( latitude: Double, longitude: Double, units: String, language: String ): Flow<WeatherResponse> { TODO("Not yet implemented") } override fun getAlerts(): Flow<List<AlertEntity>> { TODO("Not yet implemented") } override suspend fun insertAlert(alert: AlertEntity): Long { TODO("Not yet implemented") } override suspend fun deleteAlert(id: Int) { TODO("Not yet implemented") } override fun getAlert(id: Int): AlertEntity { TODO("Not yet implemented") } override fun setSharedSettings(temperature: Temperature) { TODO("Not yet implemented") } override fun setSharedSettings(windSpeed: WindSpeed) { TODO("Not yet implemented") } override fun getLastSavedWeather(): Flow<List<CashEntity>> { return flow { val network = api?.toList() if (network.isNullOrEmpty()) { emit(emptyList()) } else { emit(network) } } } override suspend fun insertMyFavourites(favourite: CashEntity) { api?.add(favourite) } override suspend fun deleteMyFavourite(favourite: CashEntity) { api?.remove(favourite) } }
WeatherForecastApp/app/src/test/java/com/example/wheatherapp/data/Repository/FakeRepositoryTest.kt
628783699
package com.example.wheatherapp.data.local import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class FakeLocalDatabaseTest( private val locations: MutableList<MyFavouriteEntity>? = mutableListOf(), private val api: MutableList<CashEntity>? = mutableListOf(), ):ILocalDatabase{ override fun getFavourites(): Flow<List<MyFavouriteEntity>> { return flow { val location = locations?.toList() if (location.isNullOrEmpty()) { emit(emptyList()) } else { emit(location) } } } override suspend fun deleteFavourite(favourite: MyFavouriteEntity) { locations?.remove(favourite) } override suspend fun insertLocation(favourite: MyFavouriteEntity) { locations?.add(favourite) } override suspend fun insertAlert(alert: AlertEntity): Long { TODO("Not yet implemented") } override fun getAlerts(): Flow<List<AlertEntity>> { TODO("Not yet implemented") } override suspend fun deleteAlerts(alert: Int) { TODO("Not yet implemented") } override fun getAlert(id: Int): AlertEntity { TODO("Not yet implemented") } override suspend fun deleteAlertByObject(item: AlertEntity) { TODO("Not yet implemented") } override fun getNetwork(): Flow<List<CashEntity>> { return flow { val network = api?.toList() if (network.isNullOrEmpty()) { emit(emptyList()) } else { emit(network) } } } override fun deleteNetWork(network: CashEntity) { api?.remove(network) } override fun insertNetWork(network: CashEntity) { api?.add(network) } }
WeatherForecastApp/app/src/test/java/com/example/wheatherapp/data/local/FakeLocalDatabaseTest.kt
2569663947
package com.example.wheatherapp.data.remote import com.example.wheatherapp.data.models.City import com.example.wheatherapp.data.models.Coord import com.example.wheatherapp.data.models.WeatherResponse import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class FakeRemoteDataSourceTest : IRemoteDataSource { override suspend fun getWeatherDetails( latitude: Double, longitude: Double, units: String, lang: String ): Flow<WeatherResponse> { return flow { emit( WeatherResponse( City(Coord(0.0, 0.0), "", 0, "", 0, 0, 0, 0), 0, "0", emptyList(), 0 ) ) } } }
WeatherForecastApp/app/src/test/java/com/example/wheatherapp/data/remote/FakeRemoteDataSourceTest.kt
1358951294
package com.example.wheatherapp.ui.home.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.wheatherapp.data.state.HomeResponseState import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.cash.Language import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.models.WeatherResponse import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch // I send Repository not context bec : depend on MVVM View should not be in ViewModel // so I send repo class HomeViewModel(private val repository: Repository):ViewModel() { // make weatherDetails private to prevent any class from update (change in ) data private val _weatherDetails = MutableStateFlow<HomeResponseState<WeatherResponse>>( HomeResponseState.OnLoading()) val weatherDetails: StateFlow<HomeResponseState<WeatherResponse>> get() = _weatherDetails // Data Came (Receive Data) fun getWeatherDetails( latitude:Double, longitude:Double , units: String, language: String,){ viewModelScope.launch { repository.getWeatherDetails(latitude,longitude , units , language) .catch { _weatherDetails.value = HomeResponseState.OnError(it.message.toString()) } // catch errors .collect{ repository.insertMyFavourites(CashEntity(weather = it)) _weatherDetails.value = HomeResponseState.OnSuccess(it) } } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/home/viewmodel/HomeViewModel.kt
2542063543
package com.example.wheatherapp.ui.home.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.wheatherapp.data.Repository.Repository import java.lang.IllegalArgumentException class HomeViewModelFactory( private val repository: Repository ):ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return if(modelClass.isAssignableFrom(HomeViewModel::class.java)){ HomeViewModel(repository) as T }else{ throw IllegalArgumentException("ViewModel Class is not Found") } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/home/viewmodel/HomeViewModelFactory.kt
2214525582
import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.wheatherapp.data.models.ListResponse import com.example.wheatherapp.data.utils.LangageSetting import com.example.wheatherapp.databinding.DayTempCardBinding import java.text.SimpleDateFormat import java.util.* class SevenDayAdapter(private val dataList: List<ListResponse>, private val unit: String) : RecyclerView.Adapter<SevenDayAdapter.UserHolder>() { private var temperatureUnit: String = unit class UserHolder(val binding: DayTempCardBinding) : RecyclerView.ViewHolder(binding.root) { private val lang: LangageSetting = LangageSetting(binding.root.context) fun bind(get: ListResponse, temperatureUnit: String) { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale(lang.getLanguage())) val outputFormat = SimpleDateFormat("EEEE", Locale(lang.getLanguage())) val date = inputFormat.parse(get.dtTxt) val formattedDay = outputFormat.format(date) binding.textCardDay.text = formattedDay Glide.with(binding.root.context) .load("https://openweathermap.org/img/wn/${get.weather?.get(0)?.icon}@2x.png") .into(binding.imageCardDayIcon) binding.textCardDayTempDescription.text = get.weather?.get(0)?.description.toString() val temperature = "${get.main?.temp?.toInt()}$temperatureUnit" binding.textCardDayTemp.text = temperature } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { val binding = DayTempCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return UserHolder(binding) } override fun onBindViewHolder(holder: UserHolder, position: Int) { val dayDataIndex = position % 7 val dayData = dataList[dayDataIndex] holder.bind(dayData, temperatureUnit) } override fun getItemCount(): Int { // Ensure that only 7 days are displayed return minOf(dataList.size, 7) } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/home/view/SevenDayAdapter.kt
291899338
package com.example.wheatherapp.ui.home.view import SevenDayAdapter import android.os.Bundle import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Color import android.net.ConnectivityManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.example.wheatherapp.connectivity.ConnectivityReceiver import com.example.wheatherapp.data.state.HomeResponseState import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.cash.getSettingsTemperature import com.example.wheatherapp.data.local.LocalDatabaseImp import com.example.wheatherapp.data.local.cash.Language import com.example.wheatherapp.data.local.cash.getSettingsLanguage import com.example.wheatherapp.data.local.cash.getSettingsUserLocation import com.example.wheatherapp.data.local.cash.getSettingsWindSpeed import com.example.wheatherapp.data.local.cash.getUnitSystem import com.example.wheatherapp.data.local.cash.getUnitSystemForWind import com.example.wheatherapp.data.utils.LangageSetting import com.example.wheatherapp.databinding.FragmentHomeBinding import com.example.wheatherapp.ui.home.viewmodel.HomeViewModel import com.example.wheatherapp.ui.home.viewmodel.HomeViewModelFactory import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale class HomeFragment : Fragment() , ConnectivityReceiver.ConnectivityReceiverListener{ // view binding of home xml private lateinit var binding: FragmentHomeBinding private lateinit var adapterDaily: SevenDayAdapter private lateinit var adapterHourly: HourlyAdapter private var units: String = "Meter" private var flagNoConnection: Boolean = false private var language: String = "en" private lateinit var lang: LangageSetting private lateinit var temperatureUnit: String private lateinit var windUnit : String private var latitude: Double = 0.0 private var longitude: Double = 0.0 lateinit var viewModel : HomeViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lang = LangageSetting(requireContext()) convertLanguage() val homeFactory = HomeViewModelFactory( Repository.getInstance( requireContext() ) ) // Take temp unit from shared preference val temperatureSetting = requireContext().getSettingsTemperature() units = getUnitSystem(temperatureSetting) setEnglishTempUnits(units) // Initialize temperatureUnit val windSetting = requireContext().getSettingsWindSpeed() units = getUnitSystemForWind(windSetting) setEnglishWindUnits(units) // Initialize temperatureUnit Log.i("units", "onViewCreated: ${units}") viewModel = ViewModelProvider(this, homeFactory)[HomeViewModel::class.java] // if (selectedLatitude != null && selectedLongitude != null) { if ( arguments != null && requireArguments().containsKey("latitude")){ latitude = requireArguments().getDouble("latitude") longitude = requireArguments().getDouble("longitude") // Location data selected from map } else { // Location data obtained from GPS val latLang = requireContext().getSettingsUserLocation() latitude = latLang.latitude longitude = latLang.longitude // Toast.makeText(requireContext(),"GPSSSSSSSSSSSSSSSSSSSSSSSS",Toast.LENGTH_SHORT).show() } viewModel.getWeatherDetails(latitude, longitude , units , language ) lifecycleScope.launch { viewModel.weatherDetails.collect { state -> when (state) { is HomeResponseState.OnSuccess->{ binding.progressBar.visibility = View.GONE // Toast.makeText(requireContext(),state.data.toString(),Toast.LENGTH_SHORT).show() binding.textCity.text = state.data.city?.name binding.textCurrentDay.text = state.data.list.get(0).let { val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale(lang.getLanguage())) val date = dateFormat.parse(it.dtTxt) val calendar = Calendar.getInstance() calendar.time = date val dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale(lang.getLanguage())) dayOfWeek } binding.textCurrentDate.text = state.data.list.get(0).let { SimpleDateFormat("dd MMM yyyy", Locale(lang.getLanguage())).format( SimpleDateFormat("yyyy-MM-dd", Locale(lang.getLanguage())).parse(it.dtTxt) ) } Glide.with(this@HomeFragment) .load("https://openweathermap.org/img/wn/${state.data.list.get(0).weather?.get(0)?.icon}@2x.png") .into(binding.imageWeatherIcon) // binding.textCurrentTempreture.text = "${state.data.list[0].main?.temp?.toInt()}$temperatureUnit" binding.textCurrentTempreture.text = "${convertTemperature(state.data.list[0].main?.temp, temperatureUnit)}$temperatureUnit" binding.textTempDescription.text = state.data.list.get(0).weather?.get(0)?.description binding.textPressure.text = state.data.list.get(0).main?.pressure.toString() binding.textClouds.text=state.data.list.get(0).clouds?.all.toString() // binding.textWindSpeed.text = state.data.list.get(0).wind?.speed.toString() // binding.textWindSpeed.text = "${state.data.list[0].wind?.speed} $windUnit" binding.textWindSpeed.text = "${convertWindSpeed(state.data.list[0].wind?.speed, units)} $windUnit" binding.textVisibility.text = state.data.list.get(0).visibility.toString() binding.textHumidity.text = state.data.list.get(0).main?.humidity.toString() // Day Adapter adapterDaily = SevenDayAdapter(state.data.list , temperatureUnit) binding.recyclerViewTempPerDay.adapter = adapterDaily // binding.recyclerViewTempPerDay.layoutManager = LinearLayoutManager(requireContext()) // Hour Adapter adapterHourly = HourlyAdapter(state.data.list , temperatureUnit) binding.recyclerViewTempPerTime.adapter=adapterHourly // binding.recyclerViewTempPerTime.layoutManager = LinearLayoutManager(requireContext()) } is HomeResponseState.OnError->{ Toast.makeText(requireContext(),state.message,Toast.LENGTH_SHORT).show() } is HomeResponseState.OnLoading->{ Toast.makeText(requireContext(),"Loading........",Toast.LENGTH_SHORT).show() binding.progressBar.visibility = View.VISIBLE } else -> {} } } } } override fun onNetworkConnectionChanged(isConnected: Boolean) { if (binding != null) { if (isConnected) { if (flagNoConnection) { val snackBar = Snackbar.make(binding.root, "Back Online", Snackbar.LENGTH_SHORT) snackBar.view.setBackgroundColor(Color.GREEN) snackBar.show() flagNoConnection = false refreshFragment() } } else { flagNoConnection = true val snackBar = Snackbar.make(binding.root, "You are offline , Check your internet", Snackbar.LENGTH_LONG) snackBar.view.setBackgroundColor(Color.RED) snackBar.show() // get from room } } } private fun refreshFragment() { val ft: FragmentTransaction = requireFragmentManager().beginTransaction() ft.setReorderingAllowed(false) ft.detach(this).attach(this).commit() } private val connectivityReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo val isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnected // Call your method to handle connectivity changes onNetworkConnectionChanged(isConnected) } } override fun onStart() { super.onStart() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply { addAction("android.net.conn.CONNECTIVITY_CHANGE") } context?.registerReceiver(connectivityReceiver, filter) } override fun onStop() { super.onStop() context?.unregisterReceiver(connectivityReceiver) } override fun onDestroyView() { super.onDestroyView() ConnectivityReceiver.connectivityReceiverListener = null } private fun setEnglishTempUnits(units: String) { temperatureUnit = when (units) { "metric" -> " °K" // Celsius "imperial" -> " °F" // Fahrenheit "standard" -> " °C" // Kelvin else -> " °C" // Default to Celsius if unknown } } private fun convertTemperature(temp: Double?, units: String): Int { Log.d("d","the unit $units") temp?.let { return when (units) { " °K" -> temp.toInt() " °F" -> ((temp * 9/5) + 32).toInt() " °C" -> (temp + 273.15).toInt() else -> temp.toInt() } } return 0 } private fun setEnglishWindUnits(units: String) { windUnit = when (units) { "imperial" -> " miles/h" "standard" -> " m/s" else -> " °m/s" } } private fun convertWindSpeed(speed: Double?, units: String): Double { speed?.let { return when (units) { "imperial" -> speed * 2.23694 // Meters per second to miles per hour "standard" -> speed // No conversion needed for meters per second else -> speed // Default to meters per second if unknown } } return 0.0 // Default value if speed is null } private fun convertLanguage() { language = lang.getLanguage() } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/home/view/HomeFragment.kt
608998611
package com.example.wheatherapp.ui.home.view import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.wheatherapp.data.models.ListResponse import com.example.wheatherapp.data.utils.LangageSetting import com.example.wheatherapp.databinding.TimeTempCardBinding import java.text.SimpleDateFormat import java.util.* class HourlyAdapter(private val dataList: List<ListResponse> , private val unit :String) : RecyclerView.Adapter<HourlyAdapter.UserHolder>() { private var temperatureUnit: String = unit class UserHolder(val binding: TimeTempCardBinding) : RecyclerView.ViewHolder(binding.root) { private val lang: LangageSetting = LangageSetting(binding.root.context) fun bind(get: ListResponse, temperatureUnit: String) { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale(lang.getLanguage())) val outputFormat = SimpleDateFormat("hh:mm a", Locale(lang.getLanguage())) val date = inputFormat.parse(get.dtTxt) val formattedTime = outputFormat.format(date) binding.textCardTime.text = formattedTime Glide.with(binding.root.context) .load("https://openweathermap.org/img/wn/${get.weather?.get(0)?.icon}@2x.png") .into(binding.imageCardTempIcon) val temperature = "${get.main?.temp?.toInt()}$temperatureUnit" binding.textCardTemp.text = temperature } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { val binding = TimeTempCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return UserHolder(binding) } override fun onBindViewHolder(holder: UserHolder, position: Int) { holder.bind(dataList[position], temperatureUnit) } override fun getItemCount(): Int { return dataList.size } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/home/view/HourlyAdapter.kt
232129226
package com.example.wheatherapp.ui.alert.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.models.WeatherResponse import com.example.wheatherapp.data.state.HomeResponseState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch // correct --------------> // we use coroutine in viewModel class AlertViewModel(private val repository: Repository) : ViewModel() { private val _stateGetAlert = MutableStateFlow<HomeResponseState<List<AlertEntity>>>( HomeResponseState.OnLoading()) val stateGetAlert: StateFlow<HomeResponseState<List<AlertEntity>>> get() = _stateGetAlert suspend fun insertAlert(alertModel: AlertEntity):Long{ return repository.insertAlert(alertModel) } fun getAlertList(){ viewModelScope.launch { repository.getAlerts() .catch { _stateGetAlert.value = HomeResponseState.OnError(it.message.toString()) } // catch errors .collect{ _stateGetAlert.value = HomeResponseState.OnSuccess(it) } } } fun removeAlert(id :Int){ viewModelScope.launch{ repository.deleteAlert(id) } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/viewmodel/AlertViewModel.kt
2630696676
package com.example.wheatherapp.ui.alert.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.wheatherapp.data.Repository.Repository import java.lang.IllegalArgumentException // use repo instead of use case class AlertViewModelFactory ( private val repository: Repository ): ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return if (modelClass.isAssignableFrom(AlertViewModel::class.java)) { AlertViewModel(repository) as T } else { throw IllegalArgumentException("ViewModel Class is not Found") } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/viewmodel/AlertViewModelFactory.kt
1982357003
package com.example.wheatherapp.ui.alert.view import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.databinding.AlertCardBinding import com.example.wheatherapp.databinding.FavoriteCardBinding import com.example.wheatherapp.dayConverterToString import com.example.wheatherapp.timeConverterToString import com.example.wheatherapp.ui.favourite.view.FavouriteAdapter class AlertAdapter( private val context: Context, private var dataList: List<AlertEntity>, private val onDeleteClicked: (AlertEntity) -> Unit // Separate click action for delete ) : RecyclerView.Adapter<AlertAdapter.UserHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { val binding = AlertCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return UserHolder(binding) } override fun onBindViewHolder(holder: UserHolder, position: Int) { val alertModel = dataList[position] // convert timeStap to human readable data and time holder.binding.textFrom.text = " ${timeConverterToString(alertModel.startTime?:0,context)}" holder.binding.textTo.text = " ${timeConverterToString(alertModel.endTime?:0,context)}" // delete action holder.binding.btnDelete.setOnClickListener{ onDeleteClicked(alertModel) } } override fun getItemCount(): Int = dataList.size fun submitList(newList: List<AlertEntity>) { dataList = newList notifyDataSetChanged() } class UserHolder(val binding: AlertCardBinding) : RecyclerView.ViewHolder(binding.root) }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/view/AlertAdapter.kt
38696534
package com.example.wheatherapp.ui.alert.view import android.app.DatePickerDialog import android.app.TimePickerDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TimePicker import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.work.Constraints import androidx.work.Data import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequest import androidx.work.WorkManager import com.example.wheatherapp.R import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cash.getSettingsUserLocation import com.example.wheatherapp.data.utils.TimeConverter import com.example.wheatherapp.databinding.FragmentAlertDialogBinding import com.example.wheatherapp.ui.alert.services.AlertPeriodicWorkManager import com.example.wheatherapp.ui.alert.viewmodel.AlertViewModel import com.example.wheatherapp.ui.alert.viewmodel.AlertViewModelFactory import kotlinx.coroutines.launch import java.util.Calendar import java.util.concurrent.TimeUnit //Correct ---------------> class Alert_dialogFragment : DialogFragment() { private val viewModel : AlertViewModel by lazy { val repository = Repository.getInstance(requireActivity().application) ViewModelProvider( requireActivity(), AlertViewModelFactory(repository) )[AlertViewModel::class.java] } private lateinit var binding : FragmentAlertDialogBinding private lateinit var weatherAlert : AlertEntity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment dialog!!.window?.setBackgroundDrawableResource(R.drawable.background_search) binding = FragmentAlertDialogBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setInitialData() binding.btnFrom.setOnClickListener { showDatePicker(true) } binding.btnTo.setOnClickListener { showDatePicker(false) } binding.btnSave.setOnClickListener { val latLang = requireContext().getSettingsUserLocation() val latitude = latLang.latitude val longitude = latLang.longitude weatherAlert.latitude = latitude weatherAlert.longitude = longitude lifecycleScope.launch { val result = viewModel.insertAlert(weatherAlert) setPeriodWorkManger(result) } dialog!!.dismiss() } binding.btnCancel.setOnClickListener { dialog!!.dismiss() } } private fun setPeriodWorkManger(id: Long) { val data = Data.Builder() data.putLong("id", id) // can handle more than one constraint val constraints = Constraints.Builder() .setRequiresBatteryNotLow(true) .build() val periodicWorkRequest = PeriodicWorkRequest.Builder( AlertPeriodicWorkManager::class.java, 24, TimeUnit.HOURS ) .setConstraints(constraints) .setInputData(data.build()) .build() WorkManager.getInstance(requireContext()).enqueueUniquePeriodicWork( "$id", ExistingPeriodicWorkPolicy.UPDATE, periodicWorkRequest ) } override fun onStart() { super.onStart() dialog!!.setCanceledOnTouchOutside(false) dialog!!.window?.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) } private fun setInitialData() { val rightNow = Calendar.getInstance() // init day val year = rightNow.get(Calendar.YEAR) val month = rightNow.get(Calendar.MONTH) val day = rightNow.get(Calendar.DAY_OF_MONTH) val date = "$day/${month + 1}/$year" val dayNow = TimeConverter.convertStringToTimestamp(date, TimeConverter.DATE_PATTERN_SLASH) // init time val currentHour = TimeUnit.HOURS.toSeconds(rightNow.get(Calendar.HOUR_OF_DAY).toLong()) val currentMinute = TimeUnit.MINUTES.toSeconds(rightNow.get(Calendar.MINUTE).toLong()) val currentTime = (currentHour + currentMinute).minus(3600L * 2) val currentTimeText = TimeConverter.convertTimestampToString((currentTime + 60), TimeConverter.TIME_PATTERN) val afterOneHour = currentTime.plus(3600L) val afterOneHourText = TimeConverter.convertTimestampToString(afterOneHour, TimeConverter.TIME_PATTERN) binding.btnFrom.text = date.plus("").plus(currentTimeText) binding.btnTo.text = date.plus("").plus(afterOneHourText) //init model weatherAlert = AlertEntity( startTime = (currentTime + 60), endTime = afterOneHour, startDate = dayNow, endDate = dayNow ) } private fun showDatePicker(isFrom: Boolean ) { val myCalender = Calendar.getInstance() val year = myCalender[Calendar.YEAR] val month = myCalender[Calendar.MONTH] val day = myCalender[Calendar.DAY_OF_MONTH] val myDateListener = DatePickerDialog.OnDateSetListener { view, year, month, day -> if (view.isShown) { val date = "$day/${month + 1}/$year" showTimePicker( isFrom, TimeConverter.convertStringToTimestamp( date, TimeConverter.DATE_PATTERN_SLASH ) ) } } val datePickerDialog = DatePickerDialog( requireContext(), android.R.style.Theme_Holo_Light_Dialog_NoActionBar, myDateListener, year, month, day ) datePickerDialog.setTitle(getString(R.string.date_picker)) datePickerDialog.window!!.setBackgroundDrawableResource(android.R.color.transparent) datePickerDialog.show() } private fun showTimePicker(isFrom: Boolean, datePicker: Long) { val rightNow = Calendar.getInstance() val currentHour = rightNow.get(Calendar.HOUR_OF_DAY) val currentMinute = rightNow.get(Calendar.MINUTE) val listener: (TimePicker?, Int, Int) -> Unit = { _: TimePicker?, hour: Int, minute: Int -> val time = TimeUnit.MINUTES.toSeconds(minute.toLong()) + TimeUnit.HOURS.toSeconds(hour.toLong()) - (3600L * 2) val dateString = TimeConverter.convertTimestampToString( datePicker, TimeConverter.DATE_PATTERN_SLASH ) val timeString = TimeConverter.convertTimestampToString(time, TimeConverter.TIME_PATTERN) val text = dateString.plus(" ").plus(timeString) if (isFrom) { weatherAlert.startTime = time weatherAlert.startDate = datePicker binding.btnFrom.text = text } else { weatherAlert.endTime = time weatherAlert.endDate = datePicker binding.btnTo.text = text } } val timePickerDialog = TimePickerDialog( requireContext(), android.R.style.Theme_Holo_Light_Dialog_NoActionBar, listener, currentHour, currentMinute, false ) timePickerDialog.setTitle(getString(R.string.time_picker)) timePickerDialog.window?.setBackgroundDrawableResource(android.R.color.transparent) timePickerDialog.show() } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/view/Alert_dialogFragment.kt
965403423
package com.example.wheatherapp.ui.alert.view import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.work.WorkManager import com.bumptech.glide.Glide import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.LocalDatabaseImp import com.example.wheatherapp.data.remote.RemoteDataSource import com.example.wheatherapp.data.state.HomeResponseState import com.example.wheatherapp.databinding.FragmentAlertBinding import com.example.wheatherapp.ui.alert.viewmodel.AlertViewModel import com.example.wheatherapp.ui.alert.viewmodel.AlertViewModelFactory import kotlinx.coroutines.launch class AlertFragment : Fragment() { private var _binding: FragmentAlertBinding? = null private val binding get() = _binding!! private lateinit var viewModel: AlertViewModel private lateinit var adapter: AlertAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentAlertBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViewModel() setupRecyclerView() setupAddAlertButton() observeViewModel() } private fun setupViewModel() { val factory = AlertViewModelFactory(Repository( RemoteDataSource.getInstance(requireContext()), LocalDatabaseImp.getInstance(requireContext()) ) ) viewModel = ViewModelProvider(this, factory).get(AlertViewModel::class.java) } private fun setupRecyclerView() { val manager = LinearLayoutManager(requireContext()) manager.orientation = RecyclerView.VERTICAL binding.alertRecyclerView.layoutManager = manager adapter = AlertAdapter(requireContext() , emptyList()) { alertEntity -> alertEntity.id?.let { id -> viewModel.removeAlert(id) WorkManager.getInstance(requireContext()).cancelAllWorkByTag(id.toString()) } } binding.alertRecyclerView.adapter = adapter } private fun observeViewModel() { viewModel.getAlertList() lifecycleScope.launch { viewModel.stateGetAlert.collect { state -> when (state) { is HomeResponseState.OnSuccess->{ Log.i("Tag", "observeViewModel: ${state.data.size}") adapter.submitList(state.data) adapter.notifyDataSetChanged() } is HomeResponseState.OnError->{ Toast.makeText(requireContext(),state.message, Toast.LENGTH_SHORT).show() } is HomeResponseState.OnLoading->{ Toast.makeText(requireContext(),"Loading........", Toast.LENGTH_SHORT).show() } else -> {} } } } } private fun setupAddAlertButton() { binding.btnAddAlert.setOnClickListener { Alert_dialogFragment().show(requireActivity().supportFragmentManager, "AlertDialog") } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/view/AlertFragment.kt
1832155114
package com.example.wheatherapp.ui.alert.services import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.ContentResolver import android.content.Intent import android.graphics.Color import android.media.AudioAttributes import android.net.Uri import android.os.Build import android.os.IBinder import android.provider.Settings import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import com.example.wheatherapp.MainActivity import com.example.wheatherapp.R // Correct --------------------------> class AlertService : Service() { private val CHANNEL_ID = 1 private val FOREGROUND_ID = 2 private var notificationManager: NotificationManager? = null var alertWindowManger: AlertWindowManager? = null @RequiresApi(Build.VERSION_CODES.M) override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) val description = intent?.getStringExtra("description") // we can add icons and ......................... notificationChannel() startForeground(FOREGROUND_ID,makeNotification(description!!)) // start window manager if (Settings.canDrawOverlays(this)){ alertWindowManger = AlertWindowManager(this,this , description) alertWindowManger!!.initializeWindowManager() } val dialogIntent = Intent(this,MainActivity::class.java) dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(dialogIntent) return START_STICKY } override fun onBind(intent: Intent): IBinder? { return null } private fun makeNotification(description: String): Notification { // val intent = Intent(applicationContext , MainActivity::class.java) // intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK val sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + this.packageName + "/" + R.raw.oh_no) return NotificationCompat.Builder( applicationContext, "$CHANNEL_ID" ) .setSmallIcon(R.drawable.notifcation) .setContentText(description) .setContentTitle("Weather Alarm") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setStyle( NotificationCompat.BigTextStyle() .bigText(description) ) .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000)) .setLights(Color.RED, 3000, 3000) .setSound(sound) .setAutoCancel(true) .setAutoCancel(true) .setContentIntent( PendingIntent.getActivity( this, 0, Intent( this, MainActivity::class.java ).apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) }, PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE //------> why must out PendingIntent ) ) .build() } private fun notificationChannel() { val sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + this.packageName + "/" + R.raw.oh_no) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name: String = "Weather App Notification" val description = "Alert Notification" val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel( "$CHANNEL_ID", name, importance ) val attributes = AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION) .build() channel.enableVibration(true) channel.description = description channel.setSound(sound,attributes) notificationManager = this.getSystemService(NotificationManager::class.java) notificationManager?.createNotificationChannel(channel) } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/services/AlertService.kt
2209983923
package com.example.wheatherapp.ui.alert.services import android.content.Context import android.content.Intent import android.os.Build import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat.startForegroundService import androidx.work.CoroutineWorker import androidx.work.WorkerParameters // step 3 ----> Correct class OneTimeWorkManager (private val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) { override suspend fun doWork(): Result { val description = inputData.getString("description")?:"No data" // can add icon startAlertService(description) return Result.success() } private fun startAlertService(description: String) { val intent = Intent(applicationContext, AlertService::class.java) intent.putExtra("description", description) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(applicationContext, intent) } else { applicationContext.startService(intent) } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/services/OneTimeWorkManager.kt
3246444064
package com.example.wheatherapp.ui.alert.services import android.content.Context import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.Data import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import androidx.work.WorkerParameters import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cash.getSettingsUserLocation import kotlinx.coroutines.flow.last import java.util.Calendar import java.util.concurrent.TimeUnit // step 4 --------> class AlertPeriodicWorkManager(private val context: Context, workerParams: WorkerParameters ) : CoroutineWorker(context, workerParams ) { val repository = Repository.getInstance(context) val unit:String = "meter" val lang:String ="en" override suspend fun doWork(): Result { val data = inputData val id = data.getLong("id", -1) val alertEntity = repository.getAlert(id.toInt()) if (alertEntity == null) { return Result.failure() } if (!isStopped) { getData(alertEntity) }else{ repository.deleteAlert(id.toInt()) WorkManager.getInstance().cancelAllWorkByTag("$id") } return Result.success() } private suspend fun getData(alert: AlertEntity) { val latLang = context.getSettingsUserLocation() val latitude = latLang.latitude val longitude = latLang.longitude val currentWeather = repository.getWeatherDetails(latitude, longitude,unit,lang).last() val delay: Long = getDelay(alert) if (currentWeather != null) { setOneTimeWorkManger( delay, alert.id, currentWeather?.list?.get(0)?.weather?.get(0)?.description?:"No Data" , ) } } private fun setOneTimeWorkManger(delay: Long, id: Int?, description: String) { val data = Data.Builder() data.putString("description", description) val constraints = Constraints.Builder() .setRequiresBatteryNotLow(true) .build() val oneTimeWorkRequest = OneTimeWorkRequest.Builder( OneTimeWorkManager::class.java, ) .setInitialDelay(delay, TimeUnit.SECONDS) .setConstraints(constraints) .setInputData(data.build()) .build() WorkManager.getInstance(context).enqueueUniqueWork( "$id", ExistingWorkPolicy.REPLACE, oneTimeWorkRequest ) } private fun getDelay(alert: AlertEntity): Long { val hour = TimeUnit.HOURS.toSeconds(Calendar.getInstance().get(Calendar.HOUR_OF_DAY).toLong()) val minute = TimeUnit.MINUTES.toSeconds(Calendar.getInstance().get(Calendar.MINUTE).toLong()) return (alert.startTime ?: 0) - ((hour + minute) - (2 * 3600L)) } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/services/AlertPeriodicWorkManager.kt
2575100344
package com.example.wheatherapp.ui.alert.services import android.content.Context import android.content.DialogInterface import android.content.Intent import android.graphics.PixelFormat import android.media.MediaPlayer import android.net.Uri import android.os.Build import android.provider.Settings import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.core.app.ActivityCompat.startActivityForResult import androidx.core.content.ContextCompat.startActivity import com.example.wheatherapp.MainActivity import com.example.wheatherapp.R import com.example.wheatherapp.databinding.AlertDisplayBinding import com.google.android.material.dialog.MaterialAlertDialogBuilder class AlertWindowManager( private val alertService : AlertService, private val context: Context, private val description: String ) { private lateinit var windowManager: WindowManager private lateinit var view : View private lateinit var binding: AlertDisplayBinding fun initializeWindowManager(){ // Check overlay permission before initializing window manager checkPermissionOfOverlay() val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater view = inflater.inflate(R.layout.alert_display, null) binding = AlertDisplayBinding.bind(view) bindViewOfAlert() val layoutFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY } else { WindowManager.LayoutParams.TYPE_PHONE } windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager val width = (context.resources.displayMetrics.widthPixels * 0.85).toInt() val params = WindowManager.LayoutParams( width, WindowManager.LayoutParams.WRAP_CONTENT, layoutFlag, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE, PixelFormat.TRANSLUCENT ) windowManager.addView(view, params) } fun intentToApp(){ val dialogIntent = Intent(context, MainActivity::class.java) dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) alertService.startActivity(dialogIntent) } private fun bindViewOfAlert(){ binding.textDescription.text = description binding.btnOk.text = "Okay" binding.btnCancelA.text = "Cancel" val mediaPlayer = MediaPlayer.create(context, R.raw.oh_no) mediaPlayer.setOnCompletionListener { it.stop() } binding.btnOk.setOnClickListener{ intentToApp() closeWindowManager() closeService() mediaPlayer.stop() } binding.btnCancelA.setOnClickListener{ closeWindowManager() closeService() mediaPlayer.stop() } } private fun closeWindowManager(){ try { (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(view) view.invalidate() (view.parent as ViewGroup).removeAllViews() } catch (e: Exception){ Log.d("Error", e.toString()) } } private fun closeService(){ context.stopService(Intent(context, AlertService::class.java)) } private fun checkPermissionOfOverlay() { if (!Settings.canDrawOverlays(context)) { val alertDialogBuilder = MaterialAlertDialogBuilder(context) alertDialogBuilder.setTitle("display on top title") .setMessage(" you should let us to draw on top") .setPositiveButton("Okay") { dialog: DialogInterface, _: Int -> // Navigate to Manage Overlay settings in device val intent = Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.packageName) ) startActivityForResult(context as MainActivity, intent, 1, null) dialog.dismiss() }.setNegativeButton("No") { dialog: DialogInterface, _: Int -> dialog.dismiss() }.show() } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/alert/services/AlertWindowManager.kt
3985927600
package com.example.wheatherapp.ui.location import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.graphics.Color import android.location.LocationManager import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat import androidx.core.location.LocationManagerCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.example.wheatherapp.PERMISSION_REQUEST_CODE import com.example.wheatherapp.R import com.example.wheatherapp.connectivity.ConnectivityReceiver import com.example.wheatherapp.data.local.cash.setSharedLocation import com.example.wheatherapp.data.models.WeatherResponse import com.example.wheatherapp.databinding.FragmentHomeBinding import com.example.wheatherapp.databinding.FragmentLocationBinding import com.example.wheatherapp.ui.home.viewmodel.HomeViewModel import com.example.wheatherapp.ui.home.viewmodel.HomeViewModelFactory import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.maps.model.LatLng import com.google.android.material.snackbar.Snackbar public class LocationFragment : Fragment(), ConnectivityReceiver.ConnectivityReceiverListener { // view binding of home xml private lateinit var binding: FragmentLocationBinding lateinit var fusedLocationProviderClient: FusedLocationProviderClient private var flagNoConnection: Boolean = false lateinit var viewModel : HomeViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentLocationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // we can take location by fusedLocationProvider --> used gms-location services library (gradle) fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireActivity()) binding.currentLocationBtn.setOnClickListener{ // val requestMultiplePermissions = registerForActivityResult( // ActivityResultContracts.RequestMultiplePermissions() // ) { permissions -> // permissions.entries.forEach { // Log.d("DEBUG", "${it.key} = ${it.value}") // getLastLocation() // } // } // // requestMultiplePermissions.launch( // arrayOf( // Manifest.permission.ACCESS_FINE_LOCATION, // Manifest.permission.ACCESS_COARSE_LOCATION // ) // ) // Check Location if (checkPermission()) { if (isEnabledLocation()) { getLastLocation() }else{ Toast.makeText(requireContext(), "you should enabled location", Toast.LENGTH_SHORT).show() } } requestPermission() } binding.mapBtn.setOnClickListener{ val bundle = Bundle().apply { putString("screen", "home") } findNavController().navigate(R.id.mapFragment , bundle) } } // Correct method after revision fun checkPermission(): Boolean { val fineLocation = ActivityCompat.checkSelfPermission( requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED val coarseLocation = ActivityCompat.checkSelfPermission( requireContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED return fineLocation && coarseLocation } // Correct method after revision fun requestPermission() { ActivityCompat.requestPermissions( requireActivity(), listOf( android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION, ).toTypedArray() , PERMISSION_REQUEST_CODE ) } // Correct method after revision override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == PERMISSION_REQUEST_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getLastLocation() } else { Toast.makeText( requireContext(), "Sorry, you should accept permission to use the app", Toast.LENGTH_SHORT ).show() } } @SuppressLint("MissingPermission") fun getLastLocation() { fusedLocationProviderClient .getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null) .addOnSuccessListener { location -> // or by navArgs findNavController().navigate(R.id.navigation_home) requireContext().setSharedLocation(LatLng(location.latitude,location.longitude)) } } fun isEnabledLocation():Boolean{ val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager return LocationManagerCompat.isLocationEnabled(locationManager) } override fun onNetworkConnectionChanged(isConnected: Boolean) { if (binding != null) { if (isConnected) { if (flagNoConnection) { val snackBar = Snackbar.make(binding.root, "Back Online", Snackbar.LENGTH_SHORT) snackBar.view.setBackgroundColor(Color.GREEN) snackBar.show() flagNoConnection = false refreshFragment() } } else { flagNoConnection = true val snackBar = Snackbar.make(binding.root, "You are offline", Snackbar.LENGTH_LONG) snackBar.view.setBackgroundColor(Color.RED) snackBar.show() // get from room } } } private fun refreshFragment() { val ft: FragmentTransaction = requireFragmentManager().beginTransaction() ft.setReorderingAllowed(false) ft.detach(this).attach(this).commit() } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/location/LocationFragment.kt
1112420702
package com.example.wheatherapp.ui.map.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.wheatherapp.data.Repository.Repository import java.lang.IllegalArgumentException class MapViewModelFactory2 ( private val repository: Repository ):ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return if(modelClass.isAssignableFrom(MapViewModel2::class.java)){ MapViewModel2(repository) as T }else{ throw IllegalArgumentException("ViewModel Class is not Found") } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/map/viewmodel/MapViewModelFactory2.kt
3056214236
package com.example.wheatherapp.ui.map.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MapViewModel2(private val repository: Repository): ViewModel() { fun setFavorite(favourite: MyFavouriteEntity) { viewModelScope.launch(Dispatchers.IO) { try { repository.insertFavourites(favourite) } catch (e: Exception) { throw e } } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/map/viewmodel/MapViewModel2.kt
161418439
package com.example.wheatherapp.ui.map.view import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Color import android.net.ConnectivityManager import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import androidx.navigation.fragment.findNavController import com.example.wheatherapp.R import com.example.wheatherapp.connectivity.ConnectivityReceiver import com.example.wheatherapp.data.local.cash.LocationProvider import com.example.wheatherapp.data.local.cash.setSharedLocation import com.example.wheatherapp.data.local.cash.setSharedSettings import com.example.wheatherapp.databinding.FragmentHomeBinding import com.example.wheatherapp.databinding.FragmentMapBinding import com.google.android.gms.common.api.Status import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import com.google.android.libraries.places.api.Places import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.api.model.TypeFilter import com.google.android.libraries.places.widget.AutocompleteSupportFragment import com.google.android.libraries.places.widget.listener.PlaceSelectionListener import com.google.android.material.snackbar.Snackbar // Make sure to move your API key to a secure place const val MAPS_API_KEY = "AIzaSyAaAZQFuvc7qAvxfK8bnl0OveOstvUjkBI" const val ZOOM_LEVEL = 15f class MapFragment : Fragment(), OnMapReadyCallback , ConnectivityReceiver.ConnectivityReceiverListener{ private lateinit var map: GoogleMap private var selectedLatitude: Double = 0.0 private var selectedLongitude: Double = 0.0 private var flagNoConnection: Boolean = false private lateinit var binding: FragmentMapBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment // return inflater.inflate(R.layout.fragment_map, container, false) binding = FragmentMapBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val mapFragment = childFragmentManager.findFragmentById(R.id.mapView) as SupportMapFragment? mapFragment?.getMapAsync(this) autoCompletePlacesAPI() } private fun autoCompletePlacesAPI() { if (!Places.isInitialized()) { Places.initialize(requireContext(), MAPS_API_KEY) } val autocompleteFragment = childFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment autocompleteFragment.setTypeFilter(TypeFilter.CITIES) autocompleteFragment.setPlaceFields(listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)) autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener { override fun onPlaceSelected(place: Place) { place.latLng?.let { map.addMarker(MarkerOptions().position(it).title(place.name)) map.moveCamera(CameraUpdateFactory.newLatLngZoom(it, ZOOM_LEVEL)) selectedLatitude = it.latitude selectedLongitude = it.longitude // Use Bundle to pass data val bundle = Bundle().apply { putDouble("latitude", selectedLatitude) putDouble("longitude", selectedLongitude) } if ( arguments != null && requireArguments().containsKey("screen")) { val sreen = requireArguments().getString("screen") if(sreen.equals("home")){ findNavController().navigate(R.id.action_mapFragment_to_navigation_home, bundle) }else{ requireContext().setSharedLocation(LatLng(selectedLatitude , selectedLongitude)) findNavController().navigate(R.id.action_mapFragment_to_navigation_settings, bundle) } } } } override fun onError(status: Status) { Log.e("MapFragment", "An error occurred: ${status.statusMessage}") Toast.makeText(requireContext(), "Error: ${status.statusMessage}", Toast.LENGTH_SHORT).show() } }) } override fun onMapReady(googleMap: GoogleMap) { map = googleMap } override fun onNetworkConnectionChanged(isConnected: Boolean) { if (binding != null) { if (isConnected) { if (flagNoConnection) { val snackBar = Snackbar.make(binding.root, "Back Online", Snackbar.LENGTH_SHORT) snackBar.view.setBackgroundColor(Color.GREEN) snackBar.show() flagNoConnection = false refreshFragment() } } else { flagNoConnection = true val snackBar = Snackbar.make(binding.root, "You are offline , Check your internet", Snackbar.LENGTH_LONG) snackBar.view.setBackgroundColor(Color.RED) snackBar.show() // get from room } } } private fun refreshFragment() { val ft: FragmentTransaction = requireFragmentManager().beginTransaction() ft.setReorderingAllowed(false) ft.detach(this).attach(this).commit() } private val connectivityReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo val isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnected // Call your method to handle connectivity changes onNetworkConnectionChanged(isConnected) } } override fun onStart() { super.onStart() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply { addAction("android.net.conn.CONNECTIVITY_CHANGE") } context?.registerReceiver(connectivityReceiver, filter) } override fun onStop() { super.onStop() context?.unregisterReceiver(connectivityReceiver) } override fun onDestroyView() { super.onDestroyView() ConnectivityReceiver.connectivityReceiverListener = null } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/map/view/MapFragment.kt
2117316467
package com.example.wheatherapp.ui.map.view data class Places( val name :String, val address : String, val latitude:Double, val langtiude:Double )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/map/view/Places.kt
2802964221
import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.wheatherapp.data.models.ListResponse import com.example.wheatherapp.databinding.DayTempCardBinding import java.text.SimpleDateFormat import java.util.* class SevenDayAdapter2(private val dataList: List<ListResponse>) : RecyclerView.Adapter<SevenDayAdapter2.UserHolder>() { class UserHolder(val binding: DayTempCardBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(get: ListResponse) { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val outputFormat = SimpleDateFormat("EEEE", Locale.getDefault()) val date = inputFormat.parse(get.dtTxt) val formattedDay = outputFormat.format(date) binding.textCardDay.text = formattedDay Glide.with(binding.root.context) .load("https://openweathermap.org/img/wn/${get.weather?.get(0)?.icon}@2x.png") .into(binding.imageCardDayIcon) binding.textCardDayTempDescription.text = get.weather?.get(0)?.description.toString() binding.textCardDayTemp.text = get.main?.temp.toString() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { val binding = DayTempCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return UserHolder(binding) } override fun onBindViewHolder(holder: UserHolder, position: Int) { val dayIndex = position % 7 val day = getDayOfWeek(dayIndex) val dayData = dataList[dayIndex] holder.bind(dayData) holder.binding.textCardDay.text = day } override fun getItemCount(): Int { return 7 } private fun getDayOfWeek(dayIndex: Int): String { val calendar = Calendar.getInstance() calendar.add(Calendar.DAY_OF_WEEK, dayIndex) val dateFormat = SimpleDateFormat("EEEE", Locale.getDefault()) return dateFormat.format(calendar.time) } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favHome/view/SevenDayAdapter.kt
1941903207
package com.example.wheatherapp.ui.favHome.view import HourlyAdapter2 import SevenDayAdapter2 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.example.wheatherapp.data.state.HomeResponseState import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.databinding.FragmentHomeBinding import com.example.wheatherapp.ui.home.viewmodel.HomeViewModel import com.example.wheatherapp.ui.home.viewmodel.HomeViewModelFactory import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Color import android.net.ConnectivityManager import androidx.fragment.app.FragmentTransaction import com.example.wheatherapp.connectivity.ConnectivityReceiver import com.google.android.material.snackbar.Snackbar class FavHomeFragment : Fragment() , ConnectivityReceiver.ConnectivityReceiverListener{ // view binding of home xml private lateinit var binding: FragmentHomeBinding private lateinit var adapterDaily: SevenDayAdapter2 private lateinit var adapterHourly: HourlyAdapter2 private var flagNoConnection: Boolean = false private var latitude: Double = 0.0 private var longitude: Double = 0.0 private var language: String = "en" private var units: String = "meter" lateinit var viewModel : HomeViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val homeFactory = HomeViewModelFactory( Repository.getInstance(requireContext() ) ) viewModel = ViewModelProvider(this, homeFactory)[HomeViewModel::class.java] if (arguments != null && requireArguments().containsKey("latitude")){ latitude = requireArguments().getDouble("latitude") longitude = requireArguments().getDouble("longitude") // Location data selected from map } viewModel.getWeatherDetails(latitude, longitude , units , language) lifecycleScope.launch { viewModel.weatherDetails.collect { state -> when (state) { is HomeResponseState.OnSuccess->{ binding.progressBar.visibility = View.GONE // Toast.makeText(requireContext(),state.data.toString(),Toast.LENGTH_SHORT).show() binding.textCity.text = state.data.city?.name binding.textCurrentDay.text = state.data.list.get(0).let { val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH) val date = dateFormat.parse(it.dtTxt) val calendar = Calendar.getInstance() calendar.time = date val dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH) dayOfWeek } binding.textCurrentDate.text = state.data.list.get(0).let { SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH).format( SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(it.dtTxt) ) } Glide.with(this@FavHomeFragment) .load("https://openweathermap.org/img/wn/${state.data.list.get(0).weather?.get(0)?.icon}@2x.png") .into(binding.imageWeatherIcon) binding.textCurrentTempreture.text = "${state.data.list[0].main?.temp?.toInt()}°C" binding.textTempDescription.text = state.data.list.get(0).weather?.get(0)?.description binding.textPressure.text = state.data.list.get(0).main?.pressure.toString() binding.textClouds.text=state.data.list.get(0).clouds?.all.toString() binding.textWindSpeed.text = state.data.list.get(0).wind?.speed.toString() binding.textVisibility.text = state.data.list.get(0).visibility.toString() binding.textHumidity.text = state.data.list.get(0).main?.humidity.toString() // Day Adapter adapterDaily = SevenDayAdapter2(state.data.list) binding.recyclerViewTempPerDay.adapter = adapterDaily // binding.recyclerViewTempPerDay.layoutManager = LinearLayoutManager(requireContext()) // Hour Adapter adapterHourly = HourlyAdapter2(state.data.list) binding.recyclerViewTempPerTime.adapter=adapterHourly // binding.recyclerViewTempPerTime.layoutManager = LinearLayoutManager(requireContext()) } is HomeResponseState.OnError->{ Toast.makeText(requireContext(),state.message,Toast.LENGTH_SHORT).show() } is HomeResponseState.OnLoading->{ binding.progressBar.visibility = View.VISIBLE Toast.makeText(requireContext(),"Loading........",Toast.LENGTH_SHORT).show() } } } } } override fun onNetworkConnectionChanged(isConnected: Boolean) { if (binding != null) { if (isConnected) { if (flagNoConnection) { val snackBar = Snackbar.make(binding.root, "Back Online", Snackbar.LENGTH_SHORT) snackBar.view.setBackgroundColor(Color.GREEN) snackBar.show() flagNoConnection = false refreshFragment() } } else { flagNoConnection = true val snackBar = Snackbar.make(binding.root, "You are offline , Check your internet", Snackbar.LENGTH_LONG) snackBar.view.setBackgroundColor(Color.RED) snackBar.show() // get from room } } } private fun refreshFragment() { val ft: FragmentTransaction = requireFragmentManager().beginTransaction() ft.setReorderingAllowed(false) ft.detach(this).attach(this).commit() } private val connectivityReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo val isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnected // Call your method to handle connectivity changes onNetworkConnectionChanged(isConnected) } } override fun onStart() { super.onStart() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply { addAction("android.net.conn.CONNECTIVITY_CHANGE") } context?.registerReceiver(connectivityReceiver, filter) } override fun onStop() { super.onStop() context?.unregisterReceiver(connectivityReceiver) } override fun onDestroyView() { super.onDestroyView() ConnectivityReceiver.connectivityReceiverListener = null } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favHome/view/FavHomeFragment.kt
712415974
import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.wheatherapp.data.models.ListResponse import com.example.wheatherapp.databinding.TimeTempCardBinding import java.text.SimpleDateFormat import java.util.* class HourlyAdapter2(private val dataList: List<ListResponse>) : RecyclerView.Adapter<HourlyAdapter2.UserHolder>() { class UserHolder(val binding: TimeTempCardBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(get: ListResponse) { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val outputFormat = SimpleDateFormat("hh:mm a", Locale.getDefault()) val date = inputFormat.parse(get.dtTxt) val formattedTime = outputFormat.format(date) binding.textCardTime.text = formattedTime Glide.with(binding.root.context) .load("https://openweathermap.org/img/wn/${get.weather?.get(0)?.icon}@2x.png") .into(binding.imageCardTempIcon) binding.textCardTemp.text = get.main?.temp.toString() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { val binding = TimeTempCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return UserHolder(binding) } override fun onBindViewHolder(holder: UserHolder, position: Int) { holder.bind(dataList[position]) } override fun getItemCount(): Int { return dataList.size } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favHome/view/HourlyAdapter.kt
3590367417
package com.example.wheatherapp.ui.favourite.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.wheatherapp.data.Repository.IRepository import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.models.WeatherResponse import com.example.wheatherapp.data.state.HomeResponseState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class FavouriteViewModel(private val repository: IRepository) : ViewModel() { private val _favouriteList = MutableStateFlow<HomeResponseState<List<MyFavouriteEntity>>>( HomeResponseState.OnLoading()) val favouriteList: StateFlow<HomeResponseState<List<MyFavouriteEntity>>> get() = _favouriteList fun getFavouriteList() { viewModelScope.launch(Dispatchers.IO) { repository.getFavourites().catch { _favouriteList.value=HomeResponseState.OnError(it.message.toString()) }.collect { _favouriteList.value = HomeResponseState.OnSuccess(it) } } } fun deleteFavourite(favourite: MyFavouriteEntity) { viewModelScope.launch { repository.deleteFavourite(favourite) getFavouriteList() } } // fun insertFavourite(favourite: MyFavouriteEntity) { // viewModelScope.launch { // repository.insertFavourites(favourite) // getFavouriteList() // } // } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favourite/viewmodel/FavouriteViewModel.kt
4047198009
package com.example.wheatherapp.ui.favourite.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.wheatherapp.data.Repository.Repository import java.lang.IllegalArgumentException class FavouriteViewModelFactory(private val repository: Repository):ViewModelProvider.Factory { // used factory to add repository as dependency in viewModel // so to add repo in viewModel as dependency be through factory and shouldn't be through constructor override fun <T : ViewModel> create(modelClass: Class<T>): T { return if(modelClass.isAssignableFrom(FavouriteViewModel::class.java)){ FavouriteViewModel(repository) as T }else{ throw IllegalArgumentException("ViewModel Class is not Found") } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favourite/viewmodel/FavouriteViewModelFactory.kt
2984267258
package com.example.wheatherapp.ui.favourite.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class DetailsViewmodel : ViewModel() { private val _selectedLocation = MutableLiveData<Pair<Double, Double>>() val selectedLocation: LiveData<Pair<Double, Double>> = _selectedLocation fun selectLocation(latitude: Double, longitude: Double) { _selectedLocation.value = Pair(latitude, longitude) } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favourite/viewmodel/DetailsViewmodel.kt
1708761251
package com.example.wheatherapp.ui.favourite.view import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.databinding.FavoriteCardBinding // //import android.view.LayoutInflater //import android.view.ViewGroup // //import androidx.recyclerview.widget.RecyclerView //import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity //import com.example.wheatherapp.databinding.FavoriteCardBinding // // //class FavouriteAdapter( //private var dataList: List<MyFavouriteEntity>, //private val onClick: (data: MyFavouriteEntity) -> Unit //) : RecyclerView.Adapter<FavouriteAdapter.UserHolder>() { // // class UserHolder(val binding: FavoriteCardBinding) : RecyclerView.ViewHolder(binding.root) // // override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { // val binding = FavoriteCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) // return UserHolder(binding) // } // // // override fun onBindViewHolder(holder: FavouriteAdapter.UserHolder, position: Int) { // var data = dataList[position] // holder.binding.textFavoriteCountry.text = data.city // holder.binding.btnDelete.setOnClickListener{ // onClick(data) // } // } // // // override fun getItemCount(): Int { // return dataList.size // } // // fun submitList(newList: List<MyFavouriteEntity>) { // dataList = newList // notifyDataSetChanged() // } //} import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView class FavouriteAdapter( private var dataList: List<MyFavouriteEntity>, private val onItemClicked: (MyFavouriteEntity) -> Unit, // Adjusted for item click private val onDeleteClicked: (MyFavouriteEntity) -> Unit // Separate click action for delete ) : RecyclerView.Adapter<FavouriteAdapter.UserHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder { val binding = FavoriteCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return UserHolder(binding) } override fun onBindViewHolder(holder: UserHolder, position: Int) { val data = dataList[position] with(holder.binding) { textFavoriteCountry.text = data.city // Set click listener for the delete button btnDelete.setOnClickListener { onDeleteClicked(data) } // Set click listener for the whole item root.setOnClickListener { onItemClicked(data) } } } override fun getItemCount(): Int = dataList.size fun submitList(newList: List<MyFavouriteEntity>) { dataList = newList notifyDataSetChanged() } class UserHolder(val binding: FavoriteCardBinding) : RecyclerView.ViewHolder(binding.root) }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favourite/view/FavouriteAdapter.kt
2284322842
package com.example.wheatherapp.ui.favourite.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.wheatherapp.R import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.LocalDatabaseImp import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.remote.RemoteDataSource import com.example.wheatherapp.data.state.HomeResponseState import com.example.wheatherapp.databinding.FragmentFavouriteBinding import com.example.wheatherapp.ui.favourite.viewmodel.FavouriteViewModel import com.example.wheatherapp.ui.favourite.viewmodel.FavouriteViewModelFactory import kotlinx.coroutines.launch class FavouriteFragment : Fragment() { private lateinit var viewModel: FavouriteViewModel private lateinit var binding: FragmentFavouriteBinding private lateinit var favFactory: FavouriteViewModelFactory private lateinit var adapter: FavouriteAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentFavouriteBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpAdapter() favFactory = FavouriteViewModelFactory( Repository( RemoteDataSource.getInstance(requireContext()), LocalDatabaseImp.getInstance(requireContext()) ) ) viewModel = ViewModelProvider(this, favFactory).get(FavouriteViewModel::class.java) lifecycleScope.launch { viewModel.favouriteList.collect { state -> when (state) { is HomeResponseState.OnSuccess->{ adapter.submitList(state.data) }is HomeResponseState.OnError->{ Toast.makeText(requireContext(),state.message, Toast.LENGTH_SHORT).show() } is HomeResponseState.OnLoading->{ Toast.makeText(requireContext(),"Loading........", Toast.LENGTH_SHORT).show() } else -> {} }}} binding.floatingActionButtonFav.setOnClickListener { findNavController().navigate(R.id.favMapFragment) } viewModel.getFavouriteList() } private fun setUpAdapter() { val manager = LinearLayoutManager(requireContext()) manager.orientation = RecyclerView.VERTICAL binding.favRecView.layoutManager = manager val onClick: (data: MyFavouriteEntity) -> Unit = { data -> viewModel.deleteFavourite(data) } val onItemClick: (MyFavouriteEntity) -> Unit = { item -> val bundle = Bundle().apply { putDouble("latitude", item.latitude) putDouble("longitude", item.longitude) } val navController = findNavController() navController.navigate(R.id.favHomeFragment , bundle) } val onDeleteClick: (MyFavouriteEntity) -> Unit = { item -> viewModel.deleteFavourite(item) } // adapter = FavouriteAdapter(emptyList(), onClick) adapter = FavouriteAdapter(emptyList(), onItemClick, onDeleteClick) binding.favRecView.adapter = adapter } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/favourite/view/FavouriteFragment.kt
2089168667
package com.example.wheatherapp.ui.setting.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.wheatherapp.data.Repository.Repository import java.lang.IllegalArgumentException class SettingViewModelFactory (private val repository: Repository): ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return if(modelClass.isAssignableFrom(SettingViewModel::class.java)){ SettingViewModel(repository) as T }else{ throw IllegalArgumentException("ViewModel Class is not Found") } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/setting/viewmodel/SettingViewModelFactory.kt
1635279935
package com.example.wheatherapp.ui.setting.viewmodel import androidx.annotation.IdRes import androidx.lifecycle.ViewModel import com.example.wheatherapp.R import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.cash.Temperature import com.example.wheatherapp.data.local.cash.WindSpeed class SettingViewModel (private val repository: Repository) : ViewModel() { fun saveWindSpeed(@IdRes id: Int? = null) { var windSpeed = WindSpeed.Meter when (id) { R.id.unit_miles -> { windSpeed = WindSpeed.Miles } R.id.unit_meter -> { windSpeed = WindSpeed.Meter } else -> { windSpeed = WindSpeed.Meter } } repository.setSharedSettings(windSpeed) } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/setting/viewmodel/SettingViewModel.kt
4240230555
package com.example.wheatherapp.ui.setting.view import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RadioButton import android.widget.RadioGroup import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.location.LocationManagerCompat import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewmodel.viewModelFactory import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.findNavController import com.example.wheatherapp.Constants import com.example.wheatherapp.MainActivity import com.example.wheatherapp.R import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.cash.Language import com.example.wheatherapp.data.local.cash.LocationProvider import com.example.wheatherapp.data.local.cash.Temperature import com.example.wheatherapp.data.local.cash.WindSpeed import com.example.wheatherapp.data.local.cash.getSettingsLanguage import com.example.wheatherapp.data.local.cash.getSettingsLocationProvider import com.example.wheatherapp.data.local.cash.setSharedSettings import com.example.wheatherapp.data.utils.LangageSetting import com.example.wheatherapp.databinding.FragmentSettingBinding import com.example.wheatherapp.ui.setting.viewmodel.SettingViewModel import com.example.wheatherapp.ui.setting.viewmodel.SettingViewModelFactory import com.example.wheatherapp.ui.location.LocationFragment import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.model.LatLng import kotlinx.coroutines.launch import java.util.Locale class SettingFragment : Fragment() { private lateinit var lanage: LangageSetting private lateinit var binding : FragmentSettingBinding private val viewModel : SettingViewModel by lazy { val repository = Repository.getInstance(requireContext()) ViewModelProvider( requireActivity(), SettingViewModelFactory(repository) ).get(SettingViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { binding = FragmentSettingBinding.inflate(inflater, container, false) lanage = LangageSetting(requireContext()) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.findViewById<RadioGroup>(R.id.radioGroupLanguage) .setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.settings_english -> { if (lanage.getLanguage() != "en") { changeLocality("en") lanage.setLanguage("en") } "en" } R.id.settings_arabic -> { if (lanage.getLanguage() != "ar") { changeLocality("ar") lanage.setLanguage("ar") } "ar" } else -> "en" } } val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireActivity()) lifecycleScope.launch { lanage.stateFlow.collect { language -> when (language) { "en" -> view.findViewById<RadioButton>(R.id.settings_english).isChecked = true "ar" -> view.findViewById<RadioButton>(R.id.settings_arabic).isChecked = true } } } if(requireContext().getSettingsLocationProvider() == LocationProvider.MAP){ binding.settingsMap.isChecked = true binding.settingsLocation.isChecked = false }else{ binding.settingsMap.isChecked = false binding.settingsLocation.isChecked = true } binding.settingsArabic.setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) { // requireContext().setSharedSettings(Language.Arabic) // changeLocality(Constants.ARABIC) // repository.setApiLocale(Locale("ar")) } } binding.settingsEnglish.setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) { // requireContext().setSharedSettings(Language.English) // changeLocality(Constants.ENGLISH) // repository.setApiLocale(Locale("en")) } } binding.settingsMap.setOnCheckedChangeListener { buttonView, isChecked -> if (isChecked) { requireContext().setSharedSettings(LocationProvider.MAP) NavHostFragment.findNavController(this).navigate( R.id.action_navigation_settings_to_mapFragment ) } } binding.unitCelsius.setOnClickListener { buttonView -> requireContext().setSharedSettings(Temperature.Celsius) } binding.unitFahrenheit.setOnClickListener { buttonView -> requireContext().setSharedSettings(Temperature.Fahrenheit) } binding.unitKelvin.setOnClickListener { buttonView -> requireContext().setSharedSettings(Temperature.Kelvin) } binding.unitMeter.setOnClickListener { requireContext().setSharedSettings(WindSpeed.Meter) } binding.unitMiles.setOnClickListener { requireContext().setSharedSettings(WindSpeed.Miles) } binding.settingsLocation.setOnClickListener { buttonView -> requireContext().setSharedSettings(LocationProvider.GPS) val locationFragment = requireActivity().supportFragmentManager.findFragmentByTag("LocationFragment") as? LocationFragment locationFragment?.getLastLocation() } } private fun changeLocality(language: String) { val locale = Locale(language) Locale.setDefault(locale) val resources = activity?.resources val configuration = resources?.configuration configuration?.setLocale(locale) resources?.updateConfiguration(configuration, resources.displayMetrics) val intentActivity = Intent(requireContext(), MainActivity::class.java) startActivity(intentActivity) } companion object { } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/setting/view/SettingFragment.kt
4231812801
package com.example.wheatherapp.ui.fav_map.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.wheatherapp.data.Repository.Repository import java.lang.IllegalArgumentException class MapViewModelFactory ( private val repository: Repository ):ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return if(modelClass.isAssignableFrom(MapViewModel::class.java)){ MapViewModel(repository) as T }else{ throw IllegalArgumentException("ViewModel Class is not Found") } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/fav_map/viewmodel/MapViewModelFactory.kt
3842379853
package com.example.wheatherapp.ui.fav_map.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MapViewModel(private val repository: Repository): ViewModel() { fun insertFavorite(favourite: MyFavouriteEntity) { viewModelScope.launch(Dispatchers.IO) { repository.insertFavourites(favourite) } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/fav_map/viewmodel/MapViewModel.kt
121455729
package com.example.wheatherapp.ui.fav_map.view import android.app.AlertDialog import android.content.DialogInterface import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.example.wheatherapp.R import com.example.wheatherapp.data.Repository.Repository import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.databinding.FragmentFavMapBinding import com.example.wheatherapp.ui.fav_map.viewmodel.MapViewModel import com.example.wheatherapp.ui.fav_map.viewmodel.MapViewModelFactory import com.example.wheatherapp.ui.map.view.MAPS_API_KEY import com.example.wheatherapp.ui.map.view.ZOOM_LEVEL import com.google.android.gms.common.api.Status import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.MarkerOptions import com.google.android.libraries.places.api.Places import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.api.model.TypeFilter import com.google.android.libraries.places.widget.AutocompleteSupportFragment import com.google.android.libraries.places.widget.listener.PlaceSelectionListener const val MAPS_API_KEY = "AIzaSyAaAZQFuvc7qAvxfK8bnl0OveOstvUjkBI" const val ZOOM_LEVEL = 15f class FavMapFragment : Fragment() , OnMapReadyCallback { private lateinit var binding: FragmentFavMapBinding // private lateinit var selectedPlace: MyFavouriteEntity private lateinit var viewModel:MapViewModel // View binding of home XML private lateinit var map: GoogleMap override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { //binding = FragmentMapBinding.inflate(inflater, container, false) binding = FragmentFavMapBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewModelFactory = MapViewModelFactory( Repository.getInstance( requireContext() ) ) viewModel = ViewModelProvider(this, viewModelFactory).get(MapViewModel::class.java) val mapFragment = childFragmentManager.findFragmentById(R.id.mapView) as SupportMapFragment mapFragment.getMapAsync(this) autoCompletePlacesAPI() } private fun autoCompletePlacesAPI() { val apiKey = MAPS_API_KEY if (!Places.isInitialized()) { Places.initialize(requireContext(), apiKey) } val autocompleteFragment = childFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment autocompleteFragment.setTypeFilter(TypeFilter.CITIES) autocompleteFragment.setPlaceFields( listOf( Place.Field.ID, Place.Field.NAME, Place.Field.PHOTO_METADATAS, Place.Field.LAT_LNG, Place.Field.ADDRESS ) ) autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener { override fun onPlaceSelected(place: Place) { place.latLng?.let { map.addMarker( MarkerOptions() .position(it) .title(place.name) ) map.moveCamera(CameraUpdateFactory.newLatLngZoom(it, ZOOM_LEVEL)) // Bundle ---> val bundle = Bundle().apply { putDouble("latitude", it.latitude) putDouble("longitude", it.longitude) putString("city",place.name) } val navController = findNavController() navController.navigate(R.id.action_favMapFragment_to_navigation_favourite , bundle) } val selectedPlace = MyFavouriteEntity( id = 0, place.address.toString(), place.latLng.latitude, place.latLng.longitude ) viewModel.insertFavorite(selectedPlace) } override fun onError(status: Status) { Log.d("TAG55", "onError: ${status.statusMessage}") Toast.makeText(requireContext(), status.toString(), Toast.LENGTH_SHORT).show() } }) } override fun onMapReady(googleMap: GoogleMap) { map = googleMap map.setOnMapLongClickListener {latlng -> checkSaveToFavourite() } } // Alert ************************/ fun checkSaveToFavourite(){ val alert: AlertDialog.Builder = AlertDialog.Builder(requireActivity()) alert.setTitle("favourite") alert.setMessage("Do you want to save this place on favourite") alert.setPositiveButton("save"){ _: DialogInterface, _:Int-> Toast.makeText(requireContext(),"data has been saved",Toast.LENGTH_SHORT).show() // handle save in room } alert.setNegativeButton("no"){_:DialogInterface,_:Int -> // dialog.dismiss() } val dialog = alert.create() dialog.show() } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/fav_map/view/FavMapFragment.kt
3331658253
package com.example.wheatherapp.ui.fav_map.view data class Places( val name :String, val address : String, val latitude:Double, val langtiude:Double )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/ui/fav_map/view/Places.kt
1292637865
package com.example.wheatherapp.splash import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import com.airbnb.lottie.LottieAnimationView import com.example.wheatherapp.MainActivity import com.example.wheatherapp.R import com.example.wheatherapp.ui.location.LocationFragment class SplashScreen : AppCompatActivity() { private lateinit var lottieAnimationView: LottieAnimationView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) lottieAnimationView = findViewById(R.id.splash) lottieAnimationView.animate().translationX(2000f).setDuration(2000).setStartDelay(2900) Handler().postDelayed({ val intent = Intent(applicationContext, MainActivity::class.java) intent.putExtra("fragment", LocationFragment::class.java.name) startActivity(intent) finish() }, 5000) } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/splash/SplashScreen.kt
1477096907
package com.example.wheatherapp import android.os.Bundle import android.view.View import android.widget.Toast import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.example.wheatherapp.databinding.ActivityMainBinding const val PERMISSION_REQUEST_CODE = 55 class MainActivity : AppCompatActivity() ,NavController.OnDestinationChangedListener{ // Testing Using Repository private lateinit var binding: ActivityMainBinding private lateinit var navView: BottomNavigationView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) navView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_main) // listen to any change in nav graph navController.addOnDestinationChangedListener(this) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration( setOf( R.id.navigation_home, R.id.navigation_favourite, R.id.navigation_notifications , R.id.navigation_settings ) ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) //************************************************************* } // save cast -> as? override fun onDestinationChanged( controller: NavController, destination: NavDestination, arguments: Bundle? ) { when(destination.id){ R.id.locationFragment , R.id.mapFragment -> { supportActionBar?.hide() navView.visibility= View.GONE } else->{ supportActionBar?.show() navView.visibility= View.VISIBLE } } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/MainActivity.kt
1870735371
package com.example.wheatherapp import android.annotation.SuppressLint import android.content.Context import android.os.Build import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.concurrent.TimeUnit @SuppressLint("SimpleDateFormat") fun dateTimeConverterTimestampToString(dt:Long,context :Context):String?{ val timeStamp = Date(TimeUnit.SECONDS.toMillis(dt)) return SimpleDateFormat("dd MMM , hh:mm aa" , getCurrentLocale(context)).format(timeStamp) } @SuppressLint("SimpleDateFormat") fun dayConverterToString(dt:Long,context :Context):String?{ val timeStamp = Date(TimeUnit.SECONDS.toMillis(dt)) return SimpleDateFormat("dd MMM" , getCurrentLocale(context)).format(timeStamp) } @SuppressLint("SimpleDataFormat") fun timeConverterToString(dt:Long,context :Context):String?{ val timeStamp = Date(TimeUnit.SECONDS.toMillis(dt)) return SimpleDateFormat("hh:mm aa" , getCurrentLocale(context)).format(timeStamp) } // to get locale is arabic or english // you can not use it and in this case will take default if arabic be arabic and if denylist be english // so its up to you fun getCurrentLocale(context: Context):Locale?{ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ context.resources.configuration.locales[0] }else{ context.resources.configuration.locale } } fun convertDateToLong(date:String,context: Context):Long{ val simpleDateFormat = SimpleDateFormat("dd/MM/YYYY ", getCurrentLocale(context)) val timestamp:Date = simpleDateFormat.parse(date) as Date return timestamp.time }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/Utils.kt
3010900622
package com.example.wheatherapp.connectivity import android.content.* import android.net.ConnectivityManager class ConnectivityReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (connectivityReceiverListener != null) { connectivityReceiverListener!!.onNetworkConnectionChanged( isConnectedOrConnecting( context ) ) } } private fun isConnectedOrConnecting(context: Context): Boolean { val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connMgr.activeNetworkInfo return networkInfo != null && networkInfo.isConnectedOrConnecting } interface ConnectivityReceiverListener { fun onNetworkConnectionChanged(isConnected: Boolean) } companion object { var connectivityReceiverListener: ConnectivityReceiverListener? = null } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/connectivity/ConnectivityReceiver.kt
1299426535
package com.example.wheatherapp.data.Repository import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.local.cash.Temperature import com.example.wheatherapp.data.local.cash.WindSpeed import com.example.wheatherapp.data.models.WeatherResponse import kotlinx.coroutines.flow.Flow interface IRepository { // Local fun getFavourites(): Flow<List<MyFavouriteEntity>> suspend fun insertFavourites(favourite: MyFavouriteEntity) suspend fun deleteFavourite(favourite: MyFavouriteEntity) // Remote suspend fun getWeatherDetails( latitude: Double, longitude: Double , units: String, language: String ): Flow<WeatherResponse> suspend fun getWeatherDetailsForAlert( latitude: Double, longitude: Double , units: String, language: String, ): Flow<WeatherResponse> fun getAlerts(): Flow<List<AlertEntity>> suspend fun insertAlert(alert: AlertEntity): Long suspend fun deleteAlert(id: Int) fun getAlert(id: Int): AlertEntity fun setSharedSettings(temperature: Temperature) fun setSharedSettings(windSpeed: WindSpeed) fun getLastSavedWeather(): Flow<List<CashEntity>> suspend fun insertMyFavourites(favourite: CashEntity) suspend fun deleteMyFavourite(favourite: CashEntity) }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/Repository/IRepository.kt
1079462342
package com.example.wheatherapp.data.Repository import android.content.Context import com.example.wheatherapp.data.local.ILocalDatabase import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.LocalDatabaseImp import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.local.cash.Temperature import com.example.wheatherapp.data.local.cash.WindSpeed import com.example.wheatherapp.data.local.cash.setSharedSettings import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.models.WeatherResponse import com.example.wheatherapp.data.remote.IRemoteDataSource import com.example.wheatherapp.data.remote.RemoteDataSource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow // why use local and remote in constructor class Repository ( private val network: IRemoteDataSource, private val local: ILocalDatabase) : IRepository { var context:Context? =null companion object { @Volatile private var instance: Repository? = null fun getInstance(context: Context): Repository { return instance ?: synchronized(this) { instance ?: buildRepository(context).also { instance = it } } } private fun buildRepository(context: Context): Repository { val retrofitInstance = RemoteDataSource.getInstance(context) // Assuming a static create method exists. val localDatabase = LocalDatabaseImp(context) return Repository(retrofitInstance, localDatabase) } } // Local override fun getFavourites(): Flow<List<MyFavouriteEntity>> { return local.getFavourites() } override suspend fun insertFavourites(favourite: MyFavouriteEntity) { local.insertLocation(favourite) } override suspend fun deleteFavourite(favourite: MyFavouriteEntity) { local.deleteFavourite(favourite) } // Remote override suspend fun getWeatherDetails( latitude: Double, longitude: Double , units: String, language: String, ) :Flow<WeatherResponse>{ return network.getWeatherDetails(latitude,longitude,units,language) } override suspend fun getWeatherDetailsForAlert( latitude: Double, longitude: Double , units: String, language: String, ):Flow<WeatherResponse>{ return network.getWeatherDetails(latitude,longitude,units,language) } ////////////////////////// Alert /////////////////// override fun getAlerts(): Flow<List<AlertEntity>> { return local.getAlerts() } override suspend fun insertAlert(alert: AlertEntity):Long { return local.insertAlert(alert) } override suspend fun deleteAlert(id: Int) { local.deleteAlerts(id) } override fun getAlert(id:Int): AlertEntity = local.getAlert(id) //********************************************************// // Setting shared preference of temperature and wind override fun setSharedSettings(temperature: Temperature) { context?.setSharedSettings(temperature) } override fun setSharedSettings(windSpeed: WindSpeed) { context?.setSharedSettings(windSpeed) } ///************************************************* ///// override fun getLastSavedWeather(): Flow<List<CashEntity>> { return local.getNetwork() } override suspend fun insertMyFavourites(favourite: CashEntity) { local.insertNetWork(favourite) } override suspend fun deleteMyFavourite(favourite: CashEntity) { local.deleteNetWork(favourite) } ////////////////////*************************************/////////////////////////// // fun setApiLocale(locale: Locale) { // val resources = appContext.resources // val configuration = resources.configuration // configuration.setLocale(locale) // resources.updateConfiguration(configuration, resources.displayMetrics) // } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/Repository/Repository.kt
833616141
package com.example.wheatherapp.data.utils import android.content.Context import com.example.wheatherapp.data.local.cash.SHARED_PREF import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow const val KEY_SELECTED_LANGUAGE = "language" class LangageSetting(context: Context) { private val sharedPreferences = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) private val editor = sharedPreferences.edit() private val _stateFlow = MutableSharedFlow<String>() val stateFlow = _stateFlow.asSharedFlow() fun setLanguage(language: String) { if (language != getLanguage()) { editor.putString(KEY_SELECTED_LANGUAGE, language).apply() _stateFlow.tryEmit(language) } } fun getLanguage(): String { return sharedPreferences.getString(KEY_SELECTED_LANGUAGE, "en")!! } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/utils/helper.kt
2854310037
package com.example.wheatherapp.data.utils import android.annotation.SuppressLint import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit class TimeConverter { companion object { const val DATETIME_PATTERN = "dd MMM, hh:mm aa" const val TIME_PATTERN_HOUR = "hh aa" const val TIME_PATTERN = "hh:mm aa" const val DAY_PATTERN = "dd MMM" const val DATE_PATTERN = "dd-MMM-yyy" // const val DATE_PATTERN_SLASH = "dd/MM/yyyy" const val DATE_PATTERN_SLASH = "d/M/yyyy" @SuppressLint("SimpleDateFormat") fun convertTimestampToString(dt: Long, type: String): String? { val timeStamp = Date(TimeUnit.SECONDS.toMillis(dt)) return SimpleDateFormat(type).format(timeStamp) } @SuppressLint("SimpleDateFormat") fun convertStringToTimestamp(dt: String, type: String): Long { return SimpleDateFormat(type).parse(dt)?.time ?: 0 } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/utils/TimeConverter.kt
15879285
package com.example.wheatherapp.data.models import android.os.Parcelable import com.google.gson.annotations.SerializedName import java.io.Serializable data class City( @SerializedName("coord") val coord: Coord?, @SerializedName("country") val country: String?, @SerializedName("id") val id: Int?, @SerializedName("name") val name: String?, @SerializedName("population") val population: Int?, @SerializedName("sunrise") val sunrise: Int?, @SerializedName("sunset") val sunset: Int?, @SerializedName("timezone") val timezone: Int? ) data class Clouds( @SerializedName("all") val all: Int? ) data class Coord( @SerializedName("lat") val lat: Double?, @SerializedName("lon") val lon: Double? ) data class ListResponse( @SerializedName("clouds") val clouds: Clouds?, @SerializedName("dt") val dt: Long?, @SerializedName("dt_txt") val dtTxt: String?, @SerializedName("main") val main: Main?, @SerializedName("pop") val pop: Double?, @SerializedName("sys") val sys: Sys?, @SerializedName("visibility") val visibility: Double?, @SerializedName("weather") val weather: List<Weather?>?, @SerializedName("wind") val wind: Wind? ) data class Main( //SerializedName --> @SerializedName("feels_like") val feelsLike: Double?, @SerializedName("grnd_level") val grndLevel: Double?, @SerializedName("humidity") val humidity: Double?, @SerializedName("pressure") val pressure:Double?, @SerializedName("sea_level") val seaLevel:Double?, @SerializedName("temp") val temp: Double?, @SerializedName("temp_kf") val tempKf: Double?, @SerializedName("temp_max") val tempMax: Double?, @SerializedName("temp_min") val tempMin: Double? ) data class Rain( @SerializedName("3h") val h: Double? ) data class Sys( @SerializedName("pod") val pod: String? ) data class Weather( @SerializedName("description") val description: String?, @SerializedName("icon") val icon: String?, @SerializedName("id") val id: Int?, @SerializedName("main") val main: String? ) data class WeatherResponse( // used SerializedName -> write name of api comp in SerializedName and // named property as i like @SerializedName("city") val city: City?= null, @SerializedName("cnt") val cnt: Int?= null, @SerializedName("cod") val cod: String?= null, @SerializedName("list") val list: List<ListResponse> = emptyList(), @SerializedName("message") val message: Int?= null, ) data class Wind( @SerializedName("deg") val deg: Int?, @SerializedName("gust") val gust: Double?, @SerializedName("speed") val speed: Double? )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/models/WeatherDetails.kt
3809172834
package com.example.wheatherapp.data.models data class AlertModel( val id: Int? = null, var latitude: Double? = null, var longitude: Double? = null, var city: String? = null, var startTime: String? = null, var endTime: String? = null, var startDate: String? = null, var endDate: String? = null, )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/models/AlertModel.kt
44545095
package com.example.wheatherapp.data.state sealed class FavouriteResponseState<T> { class OnSuccess<T>(var data: T) : FavouriteResponseState<T>() class OnError<T>(var message: String) : FavouriteResponseState<T>() class OnLoading<T> : FavouriteResponseState<T>() }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/state/FavouriteResponseState.kt
3513919408
package com.example.wheatherapp.data.state sealed class HomeResponseState<T>{ // make it generic type to be used in any other class // class OnNoLocationDetected<T> : HomeResponseState<T>() class OnSuccess<T>(var data: T) : HomeResponseState<T>() class OnError<T>(var message: String) : HomeResponseState<T>() class OnLoading<T> : HomeResponseState<T>() // class OnNothingData<T> : HomeResponseState<T>() }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/state/HomeResponseState.kt
1514514777
package com.example.wheatherapp.data.local.alert import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow //Step 2 ----- correct @Dao interface AlertDao { @Query("SELECT * FROM alerts") fun getAlerts(): Flow<List<AlertEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) // long -> for receive id // should return long to pic id of inserted row in db suspend fun insertAlert(alert: AlertEntity): Long // i use id instead of model to send to worker @Query("DELETE FROM alerts where id = :id") suspend fun deleteAlert(id: Int) @Query("SELECT * FROM alerts WHERE id = :id") fun getAlert(id: Int): AlertEntity @Delete suspend fun deleteAlertByObject(item: AlertEntity) }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/alert/AlertDao.kt
718050708
package com.example.wheatherapp.data.local.alert import androidx.room.Entity import androidx.room.PrimaryKey // Step 1 ---> correct @Entity(tableName = "alerts") data class AlertEntity( @PrimaryKey(autoGenerate = true) val id: Int? = null, var latitude: Double? = null, var longitude: Double? = null, var city: String? = null, // Mandatory var startTime: Long? = null, var endTime: Long? = null, var startDate: Long? = null, var endDate: Long? = null, var alarmType:String? = null )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/alert/AlertEntity.kt
2885142450
package com.example.wheatherapp.data.local.cash enum class Language { Arabic, English }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cash/Language.kt
2992563978
package com.example.wheatherapp.data.local.cash import com.google.android.gms.maps.model.LatLng data class Settings( var language: Language = Language.English, var temperature: Temperature = Temperature.Celsius, var windSpeed: WindSpeed = WindSpeed.Meter, var locationProvider: LocationProvider = LocationProvider.Nothing, var alertProvider: AlertProvider = AlertProvider.Notification, var userLocation: LatLng? = null, )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cash/Settings.kt
4110976662
package com.example.wheatherapp.data.local.cash import android.content.Context import android.content.SharedPreferences import com.google.android.gms.maps.model.LatLng // extension function -> // Datastore and SharedPreference const val USER_LOCATION_SETTINGS_KEY_NAME = "USER_LOCATION_SETTINGS_KEY_NAME" const val LANGUAGE_SETTINGS_KEY_NAME = "LANGUAGE_SETTINGS_KEY_NAME" const val TEMPERATURE_SETTINGS_KEY_NAME = "TEMPERATURE_SETTINGS_KEY_NAME" const val WIND_SPEED_SETTINGS_KEY_NAME = "WIND_SPEED_SETTINGS_KEY_NAME" const val LOCATION_PROVIDER_SETTINGS_KEY_NAME = "LOCATION_PROVIDER_SETTINGS_KEY_NAME" const val ALERT_PROVIDER_SETTINGS_KEY_NAME = "ALERT_PROVIDER_SETTINGS_KEY_NAME" const val SHARED_PREF = "SHARED_PREF" const val PREFERRED_LANGUAGE = "PREFERRED_LANGUAGE" const val SHARED_SETTINGS = "SHARED_SETTINGS" private const val SEPRATE = "$$" fun Context.getSharedSettings(): Settings { return Settings( language = getSettingsLanguage(), locationProvider = getSettingsLocationProvider(), alertProvider = getSettingsAlertProvider(), windSpeed = getSettingsWindSpeed(), temperature = getSettingsTemperature(), userLocation = getSettingsUserLocation() ) } fun Context.getSettingsUserLocation(): LatLng { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) val userLocation = (preferences.getString(USER_LOCATION_SETTINGS_KEY_NAME, "0.0" + SEPRATE + "0.0") ?: ("0.0" + SEPRATE + "0.0")).split(SEPRATE) return if (userLocation.size == 2) LatLng(userLocation[0].toDouble(), userLocation[1].toDouble()) else LatLng(0.0, 0.0) } fun Context.getSettingsTemperature(): Temperature { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) return enumValueOf<Temperature>( preferences.getString( TEMPERATURE_SETTINGS_KEY_NAME, Temperature.Celsius.name ) ?: Temperature.Celsius.name ) } fun getUnitSystem(temperature: Temperature): String { return when(temperature) { Temperature.Celsius -> "standard" Temperature.Fahrenheit -> "imperial" Temperature.Kelvin -> "metric" } } fun getUnitSystemForWind(wind: WindSpeed): String { return when(wind) { WindSpeed.Meter->"standard" WindSpeed.Miles->"imperial" } } fun Context.getSettingsLanguage(): Language { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) return enumValueOf<Language>( preferences.getString( LANGUAGE_SETTINGS_KEY_NAME, Language.English.name ) ?: Language.English.name ) } fun Context.getSettingsWindSpeed(): WindSpeed { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) return enumValueOf<WindSpeed>( preferences.getString( WIND_SPEED_SETTINGS_KEY_NAME, WindSpeed.Meter.name ) ?: WindSpeed.Meter.name ) } fun Context.getSettingsAlertProvider(): AlertProvider { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) return enumValueOf<AlertProvider>( preferences.getString( ALERT_PROVIDER_SETTINGS_KEY_NAME, AlertProvider.Notification.name ) ?: AlertProvider.Notification.name ) } fun Context.getSettingsLocationProvider(): LocationProvider { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) return enumValueOf<LocationProvider>( preferences.getString( LOCATION_PROVIDER_SETTINGS_KEY_NAME, LocationProvider.Nothing.name ) ?: LocationProvider.Nothing.name ) } // Settings fun Context.setSharedLocation(latlng: LatLng) { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = preferences.edit() editor.putString( USER_LOCATION_SETTINGS_KEY_NAME, latlng.latitude.toString() + SEPRATE + latlng.longitude.toString() ) editor.apply() } // Language -------------------------------------> fun Context.setSharedSettings(language: Language) { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = preferences.edit() editor.putString(LANGUAGE_SETTINGS_KEY_NAME, language.name) editor.apply() } // Temperature fun Context.setSharedSettings(temperature: Temperature) { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = preferences.edit() editor.putString(TEMPERATURE_SETTINGS_KEY_NAME, temperature.name) editor.apply() } // WindSpeed fun Context.setSharedSettings(windSpeed: WindSpeed) { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = preferences.edit() editor.putString(WIND_SPEED_SETTINGS_KEY_NAME, windSpeed.name) editor.apply() } // AlertProvider fun Context.setSharedSettings(alertProvider: AlertProvider) { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = preferences.edit() editor.putString(ALERT_PROVIDER_SETTINGS_KEY_NAME, alertProvider.name) editor.apply() } // Location Provider fun Context.setSharedSettings(locationProvider: LocationProvider) { val preferences: SharedPreferences = this.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = preferences.edit() editor.putString(LOCATION_PROVIDER_SETTINGS_KEY_NAME, locationProvider.name) editor.apply() }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cash/SharedPrefrenceManager.kt
74645824
package com.example.wheatherapp.data.local.cash enum class AlertProvider { Notification, Alert }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cash/AlertProvider.kt
1055526261
package com.example.wheatherapp.data.local.cash enum class LocationProvider { GPS, MAP, Nothing }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cash/LocationProvider.kt
3658262863
package com.example.wheatherapp.data.local.cash enum class Temperature { Kelvin, Fahrenheit, Celsius }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cash/Temperature.kt
71316811
package com.example.wheatherapp.data.local.cash enum class WindSpeed { Meter, Miles }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cash/WindSpeed.kt
2530689461
package com.example.wheatherapp.data.local.cashRoom import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface CashDao { @Query("SELECT * FROM api_table") fun getFavourites(): Flow<List<CashEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertFavourites(favourite: CashEntity) @Delete suspend fun deleteFavourite(favourite: CashEntity) }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cashRoom/CashDao.kt
3666521411
package com.example.wheatherapp.data.local.cashRoom import androidx.room.Entity import androidx.room.PrimaryKey import com.example.wheatherapp.data.models.WeatherResponse @Entity(tableName = "api_table") data class CashEntity( @PrimaryKey(autoGenerate = true) val id:Int ?=null, val weather: WeatherResponse // using Converter to save model as string in db and // convert string to model(object) when retrieve it // make converter class )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/cashRoom/CashEntity.kt
1278263213
package com.example.wheatherapp.data.local.favourite import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import kotlinx.coroutines.flow.Flow @Dao interface MyFavouritesDao { @Query("SELECT * FROM myFavourite_table") fun getFavorites(): Flow<List<MyFavouriteEntity>> @Insert (onConflict = OnConflictStrategy.IGNORE) suspend fun insertFavorite(favorite: MyFavouriteEntity) @Delete suspend fun deleteFavorite(favorite: MyFavouriteEntity) }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/favourite/MyFavouritesDao.kt
4165902915
package com.example.wheatherapp.data.local.favourite import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "myFavourite_table") data class MyFavouriteEntity( @PrimaryKey(autoGenerate = true) val id: Int , val city: String?, val latitude: Double, val longitude: Double, )
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/favourite/MyFavouriteEntity.kt
2224951877
package com.example.wheatherapp.data.local import androidx.room.TypeConverter import com.example.wheatherapp.data.models.WeatherResponse import com.google.gson.Gson class Converter { @TypeConverter fun fromStringToWeather(weather:String?): WeatherResponse?{ return weather?.let { Gson().fromJson(it, WeatherResponse::class.java) } } @TypeConverter fun fromWeatherToString(weather: WeatherResponse?):String?{ return weather?.let { Gson().toJson(it) } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/Converter.kt
422411119
package com.example.wheatherapp.data.local import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import kotlinx.coroutines.flow.Flow interface ILocalDatabase { fun getFavourites(): Flow<List<MyFavouriteEntity>> suspend fun deleteFavourite(favourite: MyFavouriteEntity) suspend fun insertLocation(favourite: MyFavouriteEntity) suspend fun insertAlert(alert: AlertEntity): Long fun getAlerts(): Flow<List<AlertEntity>> suspend fun deleteAlerts(alert: Int) fun getAlert(id: Int): AlertEntity suspend fun deleteAlertByObject(item: AlertEntity) fun getNetwork(): Flow<List<CashEntity>> fun deleteNetWork(network: CashEntity) fun insertNetWork(network: CashEntity) }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/ILocalDatabase.kt
2725623946
package com.example.wheatherapp.data.local import android.content.Context import com.example.wheatherapp.data.local.alert.AlertDao import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cashRoom.CashDao import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.local.favourite.MyFavouritesDao import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch class LocalDatabaseImp (context: Context) : ILocalDatabase { val dao: MyFavouritesDao by lazy { val db: DataBase = DataBase.invoke(context) db.myfavDao() } val daoAlert: AlertDao by lazy { val db: DataBase = DataBase.invoke(context) db.alertDao() } val daoNetWorkCall: CashDao by lazy { val db: DataBase = DataBase.invoke(context) db.favouriteDao() } companion object { private var localSource: LocalDatabaseImp? = null fun getInstance(context: Context): LocalDatabaseImp { if (localSource == null) { localSource = LocalDatabaseImp(context) } return localSource!! } } override fun getFavourites(): Flow<List<MyFavouriteEntity>> { return dao.getFavorites() } override suspend fun deleteFavourite(favourite: MyFavouriteEntity) { dao.deleteFavorite(favourite) } override suspend fun insertAlert(alert: AlertEntity):Long = daoAlert.insertAlert(alert) override fun getAlerts(): Flow<List<AlertEntity>> { return daoAlert.getAlerts() } override suspend fun deleteAlerts(alert: Int) { daoAlert.deleteAlert(alert) } override fun getAlert(id:Int): AlertEntity { return daoAlert.getAlert(id) } override suspend fun deleteAlertByObject(item : AlertEntity){ daoAlert.deleteAlertByObject(item) } //////////////// ****************** //////////////// override suspend fun insertLocation(favourite: MyFavouriteEntity) { dao.insertFavorite(favourite) } override fun getNetwork(): Flow<List<CashEntity>> { return daoNetWorkCall.getFavourites() } override fun deleteNetWork(network: CashEntity) { CoroutineScope(Dispatchers.IO).launch { daoNetWorkCall.deleteFavourite(network) } } override fun insertNetWork(network: CashEntity) { CoroutineScope(Dispatchers.IO).launch { daoNetWorkCall.insertFavourites(network) } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/LocalDatabaseImp.kt
1564115251
package com.example.wheatherapp.data.local import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.example.wheatherapp.data.local.alert.AlertDao import com.example.wheatherapp.data.local.alert.AlertEntity import com.example.wheatherapp.data.local.cashRoom.CashDao import com.example.wheatherapp.data.local.cashRoom.CashEntity import com.example.wheatherapp.data.local.favourite.MyFavouriteEntity import com.example.wheatherapp.data.local.favourite.MyFavouritesDao @Database(entities = [CashEntity::class , AlertEntity::class , MyFavouriteEntity::class], version = 4, exportSchema = false) @TypeConverters(Converter::class) // when change in your Entity(table) -> change version to prevent conflict occurrence abstract class DataBase :RoomDatabase(){ abstract fun favouriteDao(): CashDao abstract fun alertDao(): AlertDao abstract fun myfavDao(): MyFavouritesDao companion object { @Volatile // Volatile --> to be UpToDate private var instance: DataBase? = null private val LOCK = Any() operator fun invoke(context: Context) = instance ?: synchronized(LOCK) { // synchronized --> to avoid interruption if two thread call the same method instance ?: createDatabase(context).also { instance = it } } private fun createDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, DataBase::class.java, "favourite.db" ) .fallbackToDestructiveMigration() .build() } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/local/DataBase.kt
3001370546
package com.example.wheatherapp.data.remote import com.example.wheatherapp.Constants import com.example.wheatherapp.data.local.cash.Language import com.example.wheatherapp.data.models.WeatherResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query //Retrofit service interface ApiCalls { @GET("forecast") suspend fun getWeatherDetails( @Query("lat") latitude:Double, @Query("lon") longitude:Double, @Query("appid") apiKey:String = Constants.API_KEY, @Query("units") units: String, @Query("lang") lang: String, ): WeatherResponse // make return type response to check call status and handle different cases }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/remote/ApiCalls.kt
2877679734
package com.example.wheatherapp.data.remote import com.example.wheatherapp.data.models.WeatherResponse import kotlinx.coroutines.flow.Flow interface IRemoteDataSource { suspend fun getWeatherDetails( latitude: Double, longitude: Double, units: String, lang: String, ): Flow<WeatherResponse> }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/remote/IRemoteDataSource.kt
1220408014
package com.example.wheatherapp.data.remote import android.content.Context import retrofit2.Retrofit import com.example.wheatherapp.Constants import com.example.wheatherapp.data.models.WeatherResponse import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.converter.gson.GsonConverterFactory class RemoteDataSource : IRemoteDataSource { // used lazy -> didn't initialize its content unless make call to it private val retrofit: Retrofit by lazy { Retrofit.Builder() .baseUrl(Constants.BASE_URL) .client(cashAndLoggerManager()) .addConverterFactory(GsonConverterFactory.create()) .build() } val api: ApiCalls by lazy { retrofit.create(ApiCalls::class.java) } companion object { private var retrofit: RemoteDataSource? = null fun getInstance(context: Context): RemoteDataSource { if (retrofit == null) { retrofit = RemoteDataSource() } return retrofit!! } } // using interceptor logger --> to see and monitoring API calls(call response) in logcat and private fun cashAndLoggerManager(): OkHttpClient { // Logging Retrofit val interceptor = HttpLoggingInterceptor() interceptor.setLevel(HttpLoggingInterceptor.Level.BODY) return OkHttpClient.Builder() .addInterceptor(interceptor) .build() } override suspend fun getWeatherDetails( latitude: Double, longitude: Double, units: String, lang: String ): Flow<WeatherResponse> { return flow { emit( api.getWeatherDetails( latitude = latitude, longitude = longitude, lang = lang, units = units ) ) } } }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/data/remote/RemoteDataSource.kt
1374570307
package com.example.wheatherapp object Constants { const val BASE_URL = "https://api.openweathermap.org/data/2.5/" const val API_KEY = "6bd60fb0fef8d5aa574d0ba6cbc7216f" // Language Code const val ARABIC = "ar" const val ENGLISH = "en" // Var Args const val FAV_ITEM = "favoriteItem" const val MAP_DESTINATION = "MAP_DESTINATION" }
WeatherForecastApp/app/src/main/java/com/example/wheatherapp/Constants.kt
2460949742
package ru.netology.nework import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("ru.netology.nework", appContext.packageName) } }
NeWork_Diplom/app/src/androidTest/java/ru/netology/nework/ExampleInstrumentedTest.kt
1059060461
package ru.netology.nework import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
NeWork_Diplom/app/src/test/java/ru/netology/nework/ExampleUnitTest.kt
2342469494
package ru.netology.nework.dto data class MediaResponse( val url: String )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/MediaResponse.kt
1152540016
package ru.netology.nework.dto enum class EventType { OFFLINE, ONLINE }
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/EventType.kt
361571759
package ru.netology.nework.dto data class EventCreateRequest( val id: Long, val content:String, val datetime:String, val coords:Coordinates? = null, val type: EventType? = null, val attachment: Attachment? = null, val link:String? = null, val speakerIds:List<Long>? = null )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/EventCreateRequest.kt
3014211192
package ru.netology.nework.dto data class PushToken( val token: String, )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/PushToken.kt
3113504054
package ru.netology.nework.dto data class Attachment( val url: String, val type: AttachmentType )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Attachment.kt
4091619504
package ru.netology.nework.dto data class AuthenticationRequest( val login: String, val password: String )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/AuthenticationRequest.kt
2486259615
package ru.netology.nework.dto data class Coordinates( val lat:String?, val long:String? )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Coordinates.kt
4271728494
package ru.netology.nework.dto enum class AttachmentType { IMAGE, VIDEO, AUDIO }
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/AttachmentType.kt
236976423
package ru.netology.nework.dto data class UserResponse( val id: Long, val login: String, val name: String, val avatar: String? = null )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/UserResponse.kt
388420708
package ru.netology.nework.dto data class PostResponse( val id: Long, val authorId:Long, val author:String, val authorAvatar:String? = null, val authorJob:String? = null, val content:String, val published:String, val coords: Coordinates? = null, val link:String? = null, val likeOwnerIds: List<Long> = emptyList(), val mentionIds: List<Long> = emptyList(), val mentionedMe:Boolean = false, val likedByMe:Boolean = false, val attachment: Attachment? = null, val ownedByMe:Boolean = false, val users: UserPreview? = null )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/PostResponse.kt
2452842602
package ru.netology.nework.dto data class Error( val reason: String )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Error.kt
4091631834
package ru.netology.nework.dto data class Comment( val id: Long, val postId: Long, val authorId: Long, val author: String, val authorAvatar: String = "", val content: String, val published: Long, val likedByMe: Boolean, val likes: Int = 0, )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Comment.kt
947639973
package ru.netology.nework.dto data class Token( val id: Long, val token: String, )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Token.kt
2963906050
package ru.netology.nework.dto sealed interface FeedItem { val id: Long } data class Post( override val id: Long, val authorId: Long, val author: String, val authorAvatar: String? = null, val content: String, val published: String, val likedByMe: Boolean = false, val likeOwnerIds : List<Long>? = emptyList(), val coords: Coordinates? = null, val link:String? = null, val sharedByMe: Boolean = false, val countShared: Int = 999, val mentionIds: List<Long>? = emptyList(), val mentionedMe:Boolean = false, val attachment: Attachment? = null, val ownedByMe: Boolean = false, ) : FeedItem
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Post.kt
1405469011
package ru.netology.nework.dto data class PostCreateRequest( val id: Long, val content: String, val coords: Coordinates? = null, val link: String?, val attachment: Attachment? = null, val mentionIds: List<Long>? = null )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/PostCreateRequest.kt
4114211553
package ru.netology.nework.dto import java.io.File data class Media(val id: String) data class MediaUpload(val file: File)
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Media.kt
2482941589
package ru.netology.nework.dto data class User( val id: Long, val login: String, val name: String, val avatar: String? = null, )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/User.kt
3367149365
package ru.netology.nework.dto data class EventResponse( val id:Long, val authorId:Long, val author:String, val authorAvatar:String? = null, val authorJob:String? = null, val content:String, val datetime:String, val published:String, val coords:Coordinates? = null, val type:EventType, val likeOwnerIds: List<Long> = emptyList(), val likedByMe:Boolean = false, val speakerIds: List<Long> = emptyList(), val participantsIds: List<Long> = emptyList(), val participatedByMe:Boolean = false, val attachment:Attachment? = null, val link:String? = null, val ownedByMe:Boolean = false, val users: Map<String, UserPreview>? = null )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/EventResponse.kt
2595535503
package ru.netology.nework.dto data class Job( val id:Long, val name:String, val position:String, val start:String, val finish:String? = null, val link:String? = null, val ownerId:Long = -1L, )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/Job.kt
2109291871
package ru.netology.nework.dto data class UserPreview( val name: String, val avatar: String? = null )
NeWork_Diplom/app/src/main/java/ru/netology/nework/dto/UserPreview.kt
218358493
package ru.netology.nework.viewmodel import android.net.Uri import androidx.lifecycle.* import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import ru.netology.nework.api.ApiService import ru.netology.nework.auth.AppAuth import ru.netology.nework.auth.AuthState import ru.netology.nework.auxiliary.ConstantValues.noPhoto import ru.netology.nework.dto.MediaUpload import ru.netology.nework.dto.Token import ru.netology.nework.model.MediaModel import java.io.File import java.io.IOException import javax.inject.Inject @HiltViewModel class AuthViewModel @Inject constructor( private val appAuth: AppAuth, private val apiService: ApiService, ) : ViewModel() { val data: LiveData<AuthState> = appAuth .authStateFlow .asLiveData(Dispatchers.Default) val authenticated: Boolean get() = appAuth.authStateFlow.value.id != 0L private val _photo = MutableLiveData(noPhoto) val photo: LiveData<MediaModel> get() = _photo fun changePhoto(uri: Uri?, file: File?) { _photo.value = MediaModel(uri, file) } private val _dataState = MutableLiveData(-1) val dataState: LiveData<Int> get() = _dataState init { _dataState.value = -1 } suspend fun login(login: String, pass: String) { viewModelScope.launch { val token: Token try { val response = apiService.login(login, pass) if (!response.isSuccessful) { _dataState.value = 1 //throw ApiError(response.code(), response.message()) } else { token = response.body() ?: Token(id = 0, token = "") appAuth.setAuth(token.id, token.token, null) _dataState.value = 0 } } catch (e: IOException) { _dataState.value = 2 //throw NetworkError } catch (e: Exception) { _dataState.value = 3 //throw UnknownError } } } suspend fun registerWithPhoto(login: String, pass: String, name: String, upload: MediaUpload?) { viewModelScope.launch { val token: Token try { val response = if (upload != null) { apiService.registerWithPhoto( login.toRequestBody("text/plain".toMediaType()), pass.toRequestBody("text/plain".toMediaType()), name.toRequestBody("text/plain".toMediaType()), MultipartBody.Part.createFormData( "file", upload.file.name, upload.file.asRequestBody() ) ) } else { apiService.register(login,pass,name) } if (!response.isSuccessful) { _dataState.value = 1 //throw ApiError(response.code(), response.message()) } else { token = response.body() ?: Token(id = 0, token = "") appAuth.setAuth(token.id, token.token, null) _dataState.value = 0 } } catch (e: IOException) { _dataState.value = 2 //throw NetworkError } catch (e: Exception) { _dataState.value = 3 //throw UnknownError } } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/viewmodel/AuthViewModel.kt
1337195759
package ru.netology.nework.viewmodel import android.app.Application import android.net.Uri import androidx.core.net.toFile import androidx.core.net.toUri import androidx.lifecycle.* import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import ru.netology.nework.auxiliary.ConstantValues.emptyEvent import ru.netology.nework.auxiliary.ConstantValues.noPhoto import ru.netology.nework.dto.* import ru.netology.nework.model.MediaModel import ru.netology.nework.repository.* import ru.netology.nework.auxiliary.SingleLiveEvent import java.io.File import javax.inject.Inject @HiltViewModel class EventViewModel @Inject constructor( application: Application, private val repository: Repository, ) : AndroidViewModel(application) { val data: Flow<List<EventResponse>> get() = flow { while (true) { loadEvents() emit(_data) delay(1_000) } } private var _data: List<EventResponse> = listOf() private val edited = MutableLiveData(emptyEvent) private val _eventCreated = SingleLiveEvent<Unit>() val eventCreated: LiveData<Unit> get() = _eventCreated private val _media = MutableLiveData( MediaModel( edited.value?.attachment?.url?.toUri(), edited.value?.attachment?.url?.toUri()?.toFile(), edited.value?.attachment?.type ) ) val media: LiveData<MediaModel> get() = _media fun changeMedia(uri: Uri?, file: File?, attachmentType: AttachmentType?) { _media.value = MediaModel(uri, file, attachmentType) } init { loadEvents() } fun loadEvents() = viewModelScope.launch { try { repository.getAllEvents() } catch (_: Exception) { } repository.dataEvents.collectLatest { _data = it } } fun likeById(eventResponse: EventResponse) = viewModelScope.launch { try { repository.likeByIdEvents(eventResponse) } catch (_: Exception) { } } fun removeById(id: Long) = viewModelScope.launch { try { repository.removeEventsById(id) } catch (_: Exception) { } } fun edit(eventResponse: EventResponse) { edited.value = eventResponse } fun getEditedId(): Long { return edited.value?.id ?: 0 } fun getEditedEventAttachment(): Attachment? { return edited.value?.attachment } fun changeContent(content: String, link: String?, datetime:String, type: EventType, speakerIds: List<Long>) { val text = content.trim() if (edited.value?.content == text && edited.value?.link == link && edited.value?.datetime == datetime && edited.value?.type == type && edited.value?.speakerIds == speakerIds) return edited.value = edited.value?.copy(content = text, link = link, datetime = datetime, type=type, speakerIds = speakerIds) } fun deleteAttachment() { edited.value = edited.value?.copy(attachment = null) } fun joinById(eventResponse: EventResponse) = viewModelScope.launch { try { repository.joinByIdEvents(eventResponse) } catch (_: Exception) { } } fun save() { edited.value?.let { savingEvents -> _eventCreated.value = Unit viewModelScope.launch { try { when (_media.value) { noPhoto -> repository.saveEvents(savingEvents) else -> _media.value?.file?.let { file -> repository.saveEventsWithAttachment( savingEvents, MediaUpload(file), _media.value!!.attachmentType!! ) } } } catch (_: Exception) { } } } edited.value = emptyEvent _media.value = noPhoto } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/viewmodel/EventViewModel.kt
10666825