content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.main.activities
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.example.main.R
import com.example.main.models.CompanyModel
import com.google.firebase.database.FirebaseDatabase
class companyProfile : AppCompatActivity() {
private lateinit var tvComName: TextView
private lateinit var tvCountry: TextView
private lateinit var tvState: TextView
private lateinit var tvEmail: TextView
private lateinit var tvUsername: TextView
private lateinit var tvPassword: TextView
private lateinit var btnUpdate: Button
private lateinit var btnDelete: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_company_profile)
initView()
setValuesToViews()
btnUpdate.setOnClickListener {
openUpdateDialog(
intent.getStringExtra("comid").toString(),
intent.getStringExtra("comName").toString(),
)
}
btnDelete.setOnClickListener {
deleteRecord(
intent.getStringExtra("comId").toString()
)
}
}
private fun deleteRecord(
id :String
)
{
val dbRef = FirebaseDatabase.getInstance().getReference("Company").child(id)
val mTask = dbRef.removeValue()
mTask.addOnSuccessListener {
Toast.makeText(this,"Company data deleted!",Toast.LENGTH_LONG).show()
val intent = Intent(this,FetchingActivity::class.java)
finish()
startActivity(intent)
}.addOnFailureListener{error->
Toast.makeText(this,"Deleting ERR ${error.message}",Toast.LENGTH_LONG).show()
}
}
private fun initView(){
tvComName = findViewById(R.id.textViewTextPersonName2)
tvCountry = findViewById(R.id.textViewTextPersonName3)
tvState = findViewById(R.id.textViewTextPersonName4)
tvEmail = findViewById(R.id.textViewTextEmailAddress)
tvUsername = findViewById(R.id.textViewTextPersonName5)
tvPassword = findViewById(R.id.textViewTextPassword2)
btnUpdate = findViewById(R.id.button10)
btnDelete = findViewById(R.id.button11)
}
private fun setValuesToViews() {
tvComName.text = intent.getStringExtra("comName")
tvCountry.text = intent.getStringExtra("country")
tvState.text = intent.getStringExtra("state")
tvEmail.text = intent.getStringExtra("email")
tvUsername.text = intent.getStringExtra("username")
tvPassword.text = intent.getStringExtra("password")
}
private fun openUpdateDialog(
comId: String,
comName: String
) {
val mDialog = AlertDialog.Builder(this)
val inflater = layoutInflater
val mDialogView = inflater.inflate(R.layout.activity_update_dialog, null)
mDialog.setView(mDialogView)
val etComName = mDialogView.findViewById<EditText>(R.id.editTextTextPersonName2)
val etCountry = mDialogView.findViewById<EditText>(R.id.editTextTextPersonName3)
val etState = mDialogView.findViewById<EditText>(R.id.editTextTextPersonName4)
val etEmail = mDialogView.findViewById<EditText>(R.id.editTextTextEmailAddress)
val etUsername = mDialogView.findViewById<EditText>(R.id.editTextTextPersonName5)
val etPassword = mDialogView.findViewById<EditText>(R.id.editTextTextPassword2)
val btnUpdate = mDialogView.findViewById<Button>(R.id.button10)
etComName.setText(intent.getStringExtra("comName").toString())
etCountry.setText(intent.getStringExtra("country").toString())
etState.setText(intent.getStringExtra("state").toString())
etEmail.setText(intent.getStringExtra("email").toString())
etUsername.setText(intent.getStringExtra("username").toString())
etPassword.setText(intent.getStringExtra("password").toString())
mDialog.setTitle("updating $comName Record")
val alertDialog = mDialog.create()
alertDialog.show()
btnUpdate.setOnClickListener {
updateComData(
comId,
etComName.text.toString(),
etCountry.text.toString(),
etState.text.toString(),
etEmail.text.toString(),
etUsername.text.toString(),
etPassword.text.toString()
)
Toast.makeText(applicationContext, "Company Data Updated", Toast.LENGTH_LONG).show()
tvComName.text = etComName.text.toString()
tvCountry.text = etCountry.text.toString()
tvState.text = etState.text.toString()
tvEmail.text = etEmail.text.toString()
tvUsername.text = etUsername.text.toString()
tvPassword.text = etPassword.text.toString()
alertDialog.dismiss()
}
}
private fun updateComData(
id: String,
name: String,
country: String,
state: String,
email: String,
username: String,
password: String,
){
val dbRef = FirebaseDatabase.getInstance().getReference("Company").child(id)
val comInfo = CompanyModel(id, name, country, state, email, username, password)
dbRef.setValue(comInfo)
}
} | Mad-Project-Kotlin/companyProfile.kt | 1824635889 |
package com.example.main.activities
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.main.models.CompanyModel
import com.example.main.R
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
class companyRegister : AppCompatActivity() {
private lateinit var etComName: EditText
private lateinit var etCountry: EditText
private lateinit var etState: EditText
private lateinit var etEmail: EditText
private lateinit var etUsername: EditText
private lateinit var etPassword: EditText
private lateinit var btnRegister: Button
private lateinit var dbRef: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_company_register)
etComName = findViewById(R.id.editTextTextPersonName2)
etCountry = findViewById(R.id.editTextTextPersonName3)
etState = findViewById(R.id.editTextTextPersonName4)
etEmail = findViewById(R.id.editTextTextEmailAddress)
etUsername = findViewById(R.id.editTextTextPersonName5)
etPassword = findViewById(R.id.editTextTextPassword2)
btnRegister = findViewById(R.id.button10)
dbRef = FirebaseDatabase.getInstance().getReference("Company")
btnRegister.setOnClickListener {
saveCompanyData()
val intent = Intent(this, FetchingActivity::class.java )
startActivity(intent)
}
}
private fun saveCompanyData() {
val comName = etComName.text.toString()
val country = etCountry.text.toString()
val state = etState.text.toString()
val email = etEmail.text.toString()
val username = etUsername.text.toString()
val password = etPassword.text.toString()
if(comName.isEmpty() || country.isEmpty() || state.isEmpty() || email.isEmpty() || username.isEmpty() || password.isEmpty()) {
if (comName.isEmpty()) {
etComName.error = "please enter Company Name"
}
if (country.isEmpty()) {
etCountry.error = "please enter Country"
}
if (state.isEmpty()) {
etState.error = "please enter State"
}
if (email.isEmpty()) {
etEmail.error = "please enter E-mail"
}
if (username.isEmpty()) {
etUsername.error = "please enter Username"
}
if (password.isEmpty()) {
etPassword.error = "please enter Password"
}
Toast.makeText(this, "Enter valid details", Toast.LENGTH_LONG).show()
}else if( password.length < 6){
etPassword.error = "Enter valid password"
Toast.makeText(this, "Enter valid password", Toast.LENGTH_LONG).show()
}
val comId = dbRef.push().key!!
val company = CompanyModel(comId, comName, country, state, email, username, password)
dbRef.child(comId).setValue(company)
.addOnCompleteListener {
Toast.makeText(this, "Data inserted successfully", Toast.LENGTH_LONG).show()
etComName.text.clear()
etCountry.text.clear()
etState.text.clear()
etEmail.text.clear()
etUsername.text.clear()
etPassword.text.clear()
}.addOnFailureListener{ err ->
Toast.makeText(this, "Error ${err.message}", Toast.LENGTH_LONG).show()
}
}
} | Mad-Project-Kotlin/companyRegister.kt | 1986849481 |
package com.example.main.activities
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.example.main.R
class landingpage : AppCompatActivity() {
private lateinit var btnsignin: Button
private lateinit var btnregisternow: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_landingpage)
btnsignin = findViewById(R.id.button8)
btnregisternow = findViewById(R.id.button9)
btnsignin.setOnClickListener {
val intent = Intent(this, FetchingActivity::class.java )
startActivity(intent)
}
btnregisternow.setOnClickListener {
val intent = Intent(this, companyRegister::class.java )
startActivity(intent)
}
}
} | Mad-Project-Kotlin/landingpage.kt | 1454420989 |
package com.example.main.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.main.R
class UpdateDialog : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_update_dialog)
}
} | Mad-Project-Kotlin/UpdateDialog.kt | 58727356 |
package com.example.rectificadoragarza.ui.home
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.example.rectificadoragarza.R
import com.example.rectificadoragarza.databinding.FragmentHomeBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null;
private val binding get() = _binding!!; //se sobre escribe el get
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentHomeBinding.inflate(layoutInflater, container, false);
return binding.root;
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initUI();
}
private fun initUI() {
binding.btnConfig.setOnClickListener {
findNavController().navigate(HomeFragmentDirections.actionHomeFragmentToConfigurationFragment());
}
binding.btnConfi.setOnClickListener{
findNavController().navigate(HomeFragmentDirections.actionHomeFragmentToServicesFragment());
}
}
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/ui/home/HomeFragment.kt | 2386746936 |
package com.example.rectificadoragarza.ui
import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import com.example.rectificadoragarza.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : FragmentActivity() {
private lateinit var binding: ActivityMainBinding;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater);
setContentView(binding.root);
initUi();
}
private fun initUi() {
Toast.makeText(this, "Bienvenido!!", Toast.LENGTH_LONG).show();
}
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/ui/MainActivity.kt | 81881369 |
package com.example.rectificadoragarza.ui.config
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rectificadoragarza.databinding.FragmentConfigurationBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ConfigurationFragment : Fragment() {
private var _binding:FragmentConfigurationBinding? = null;
private val binding get() = _binding!!; //se sobre escribe el get
override fun onCreateView( //Este crea la vista
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentConfigurationBinding.inflate(layoutInflater, container, false);
return binding.root;
}
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/ui/config/ConfigurationFragment.kt | 1627489366 |
package com.example.rectificadoragarza.ui.rgServices
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.rectificadoragarza.domain.IRepository
import com.example.rectificadoragarza.domain.usecase.GetConnecionUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class ServicesViewModel @Inject constructor(private val getConnecionUseCase: GetConnecionUseCase):ViewModel(){
private var _state = MutableStateFlow<ServicesState>(ServicesState.Loading); //stado inical
val state:StateFlow<ServicesState> = _state; //mandamos un estado inicial
fun getStatusConnection(){
//Hilo de UI
viewModelScope.launch {//Nuevo Hilo secundario
_state.value = ServicesState.Loading;
withContext(Dispatchers.IO){
val result = getConnecionUseCase();//getConnecionUseCase();
if(result!=null){
_state.value = ServicesState.Success(result.status.toString());
}else{
_state.value = ServicesState.Error("Error Interno Revice Su Conexión");
}
}
}
}
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/ui/rgServices/ServicesViewModel.kt | 1001696015 |
package com.example.rectificadoragarza.ui.rgServices
//Estados y valores
sealed class ServicesState {
data object Loading:ServicesState();
data class Error(val error:String):ServicesState();
data class Success(val data:String):ServicesState();
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/ui/rgServices/ServicesState.kt | 1689839057 |
package com.example.rectificadoragarza.ui.rgServices
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.rectificadoragarza.databinding.FragmentServicesBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
@AndroidEntryPoint
class ServicesFragment : Fragment() {
private var _binding:FragmentServicesBinding? = null;
private val binding get() = _binding!!;
//Conexion de viewModel
private val servicesViewModel by viewModels<ServicesViewModel>(); //delegamos la conexion con el viewModel a by viewModels
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentServicesBinding.inflate(layoutInflater, container, false);
return binding.root;
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initUI();
servicesViewModel.getStatusConnection();
}
private fun initUI() {
initUIState();
}
private fun initUIState() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED){
servicesViewModel.state.collect{
when(it){
ServicesState.Loading -> loadingState();
is ServicesState.Error -> errorState(it);
is ServicesState.Success -> successState(it);
}
}
}
}
}
private fun loadingState() {
binding.layoutLoading.isVisible = true;
}
private fun errorState(servicesState: ServicesState.Error) {
binding.layoutLoading.isVisible = false;
binding.textView.text = servicesState.error;
}
private fun successState(servicesState: ServicesState.Success) {
binding.layoutLoading.isVisible = false;
binding.textView.text = servicesState.data;
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/ui/rgServices/ServicesFragment.kt | 295099224 |
package com.example.rectificadoragarza
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
public class RectificadoraGarzaApp:Application() | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/RectificadoraGarzaApp.kt | 489770786 |
package com.example.rectificadoragarza.data.network.response
import com.example.rectificadoragarza.domain.model.StatusConecctionModel
import com.google.gson.annotations.SerializedName
data class StatusConnectionResponse (@SerializedName("status") val status:Int) {
//Es una funcion de extencion que nos ayudar a mapear datos
fun toDomain(): StatusConecctionModel {
return StatusConecctionModel(status = status); //es casi similar al operador cast de c#
}
}; | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/data/network/response/StatusConnectionResponse.kt | 4115891913 |
package com.example.rectificadoragarza.data.network.response
import com.google.gson.annotations.SerializedName
/*
{
"id": 1,
"nombre": "Pantalla Uno",
"estado": 1
},*/
data class ScreenResponse (
@SerializedName("id") val id:Int,
@SerializedName("nombre") val name:String,
@SerializedName("estado") val status:Int,
); | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/data/network/response/ScreenResponse.kt | 3370834068 |
package com.example.rectificadoragarza.data.network
import com.example.rectificadoragarza.data.Repository
import com.example.rectificadoragarza.domain.IRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Provides
@Singleton //Hace referencia al patron de diseño
fun provideRetrofit():Retrofit{
return Retrofit
.Builder()
.baseUrl("http://192.168.1.68/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
@Provides //Inyeccion entre provedores
fun provideRGServicesApiServices(retrofit: Retrofit): RGServicesApiServices{
return retrofit.create(RGServicesApiServices::class.java);
}
@Provides
fun provideRepository(apiServices: RGServicesApiServices):IRepository{
return Repository(apiServices);
}
//Esto es un poco mas parecido a C# definimos que queremos retornar un IRepositorio
//y retornamos el servicio que lo implemente
}
//Para poder inyectar librerias e interfaces, dagger pone a
//disposicion artefactos de nombre "Modulos", los cuales se definen
// con la etiqueta "@Module" y definir el alcance con @InstallIn
//Nota
//En pocas palabras los modulos son clases especiales que exponen metodos "provedores"
//que retornan objetos, los metodos inyectan los servicios por asi decir.
| Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/data/network/NetworkModule.kt | 3774756038 |
package com.example.rectificadoragarza.data.network
import com.example.rectificadoragarza.data.network.response.ScreenResponse
import com.example.rectificadoragarza.data.network.response.StatusConnectionResponse
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
interface RGServicesApiServices {
//Definimos las rutas que retrofit accedera;
@GET("api/talleres")
suspend fun checkConnection() : StatusConnectionResponse;//se usa suspen dado a que es una corrutina
@GET("api/talleres/listaPantallas")
suspend fun screenslist() : List<ScreenResponse>;
//@GET("api/talleres/{id}")
//suspend fun getScreen(@Path("id") result: String)
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/data/network/RGServicesApiServices.kt | 3746651134 |
package com.example.rectificadoragarza.data
import android.util.Log
import com.example.rectificadoragarza.data.network.RGServicesApiServices
import com.example.rectificadoragarza.domain.IRepository
import com.example.rectificadoragarza.domain.model.StatusConecctionModel
import javax.inject.Inject
class Repository @Inject constructor(private val apiServices: RGServicesApiServices) : IRepository{
override suspend fun getConnection(): StatusConecctionModel? {
kotlin.runCatching {
apiServices.checkConnection()
}.onSuccess{
return it.toDomain();
}.onFailure {
Log.i("Error Repositorio", "Ha ocurrido un error ${it.message}")
}
return null;
}
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/data/Repository.kt | 3841767735 |
package com.example.rectificadoragarza.domain
import com.example.rectificadoragarza.data.network.response.StatusConnectionResponse
import com.example.rectificadoragarza.domain.model.StatusConecctionModel
interface IRepository {
suspend fun getConnection(): StatusConecctionModel?;
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/domain/IRepository.kt | 829592081 |
package com.example.rectificadoragarza.domain.model
data class StatusConecctionModel(val status:Int); | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/domain/model/StatusConecctionModel.kt | 535407993 |
package com.example.rectificadoragarza.domain.usecase
import com.example.rectificadoragarza.domain.IRepository
import javax.inject.Inject
class GetConnecionUseCase @Inject constructor(private val repository: IRepository) {
//con "operator invoke" hace que una clase se comporte como una funcion,
//asi podemo acceder directamente
suspend operator fun invoke() = repository.getConnection();
} | Rectificadora-Garza-TV/app/src/main/java/com/example/rectificadoragarza/domain/usecase/GetConnecionUseCase.kt | 943068767 |
fun main(args: Array<String>) {
println("Hello World!")
// Try adding program arguments via Run/Debug configuration.
// Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html.
println("Program arguments: ${args.joinToString()}")
} | Cajero1/src/main/kotlin/Main.kt | 3350697704 |
package com.example.b2110941_communicationofdream
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("com.example.b2110941_communicationofdream", appContext.packageName)
}
} | Dream_Socialize/app/src/androidTest/java/com/example/b2110941_communicationofdream/ExampleInstrumentedTest.kt | 2766116758 |
package com.example.b2110941_communicationofdream
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)
}
} | Dream_Socialize/app/src/test/java/com/example/b2110941_communicationofdream/ExampleUnitTest.kt | 353957821 |
package com.example.b2110941_communicationofdream.apis
import com.example.b2110941_communicationofdream.models.UserResponse
import com.example.b2110941_communicationofdream.models.RequestAddWish
import com.example.b2110941_communicationofdream.models.RequestDeleteWish
import com.example.b2110941_communicationofdream.models.RequestRegisterOrLogin
import com.example.b2110941_communicationofdream.models.RequestUpdateWish
import com.example.b2110941_communicationofdream.models.ResponseMessage
import com.example.b2110941_communicationofdream.models.Wish
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.HTTP
import retrofit2.http.PATCH
import retrofit2.http.POST
class Constants{
companion object{
private const val BASE_URL = "http://158.178.227.41:6868/api/"
fun getInstance(): ApiService{ //Tham chiếu đến API
return Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL).build().create(ApiService::class.java)
}
}
}
interface ApiService {
@GET("wishes") //Phương thức
suspend fun getWishList(): Response<List<Wish>>
@POST("wishes")
suspend fun addWish(@Body addWish : RequestAddWish):
Response<ResponseMessage>
@PATCH("wishes")
suspend fun updateWish(@Body updateWish : RequestUpdateWish):
Response<ResponseMessage>
@HTTP(method = "DELETE", path = "wishes", hasBody = true)
suspend fun deleteWish(@Body deleteWish: RequestDeleteWish):
Response<ResponseMessage>
@POST("users/register")
suspend fun registerUser(@Body request: RequestRegisterOrLogin):
Response<UserResponse>
@POST("users/login")
suspend fun loginUser(@Body request: RequestRegisterOrLogin):
Response<UserResponse>
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/apis/ApiService.kt | 256805686 |
package com.example.b2110941_communicationofdream.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.example.b2110941_communicationofdream.R
import com.example.b2110941_communicationofdream.apis.Constants
import com.example.b2110941_communicationofdream.databinding.FragmentUpdateBinding
import com.example.b2110941_communicationofdream.models.RequestUpdateWish
import com.example.b2110941_communicationofdream.sharepreferences.AppSharedPreferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class UpdateFragment : Fragment() {
private lateinit var binding: FragmentUpdateBinding
private lateinit var mAppSharedPreferences: AppSharedPreferences
private var idUser = ""
private var idWish = ""
private var fullName = ""
private var content = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentUpdateBinding.inflate(layoutInflater,container,false)
mAppSharedPreferences = AppSharedPreferences(requireContext())
idUser = mAppSharedPreferences.getIdUser("idUser").toString()
idWish = mAppSharedPreferences.getWish("idWish").toString()
fullName = mAppSharedPreferences.getWish("fullname").toString()
content = mAppSharedPreferences.getWish("content").toString()
//Thiet lap nd len giao dien
binding.edtFullName.setText(fullName)
binding.edtContent.setText(content)
binding.apply {
btnSave.setOnClickListener {
fullName = edtFullName.text.toString().trim()
content = edtContent.text.toString().trim()
updateWish(fullName,content)
}
}
return binding.root
}
private fun updateWish(fullname:String, content:String){
binding.progressBar.visibility = View.VISIBLE
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main){
val response = Constants.getInstance()
.updateWish(RequestUpdateWish(idUser,idWish,fullName,content)).body()
if (response != null){
if (response.success){
binding.progressBar.visibility = View.VISIBLE
Toast.makeText(requireContext(), response.message, Toast.LENGTH_SHORT)
.show()
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout,WishListFragment()).commit()
}
}
}
}
}
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/fragments/UpdateFragment.kt | 627622733 |
package com.example.b2110941_communicationofdream.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.b2110941_communicationofdream.R
import com.example.b2110941_communicationofdream.databinding.FragmentLoginBinding
import com.example.b2110941_communicationofdream.sharepreferences.AppSharedPreferences
import com.example.b2110941_communicationofdream.apis.Constants
import com.example.b2110941_communicationofdream.models.RequestRegisterOrLogin
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
private lateinit var mAppSharedPreferences: AppSharedPreferences
private var username = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentLoginBinding.inflate(layoutInflater,container,false)
mAppSharedPreferences = AppSharedPreferences(requireContext())
binding.apply {
tvSignup.setOnClickListener{
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout, RegisterFragment()).commit()
}
btnLogin.setOnClickListener {
if (etUsername.text.isNotEmpty()){
username = etUsername.text.toString().trim()
loginUser(username)
}
}
}
return binding.root
}
private fun loginUser(username:String){
binding.apply {
progressBar.visibility = View.VISIBLE
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main){
val response = Constants.getInstance()
.loginUser(RequestRegisterOrLogin(username)).body()
if (response != null){
if(response.success){
//Đăng nhập thành công
//Nhận idUser và thực hiện lưu vào sharedPreference
mAppSharedPreferences.putIdUser("idUser", response.idUser!!)
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout, WishListFragment())
.commit()
progressBar.visibility = View.GONE
}
else{
//Đăng nhập thất bại
tvMessage.text = response.message
tvMessage.visibility = View.VISIBLE
progressBar.visibility = View.GONE
}
}
}
}
}
}
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/fragments/LoginFragment.kt | 1109613545 |
package com.example.b2110941_communicationofdream.fragments
import android.os.Bundle
import android.text.style.UpdateLayout
import com.example.b2110941_communicationofdream.apis.Constants
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.FragmentContainer
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.b2110941_communicationofdream.R
import com.example.b2110941_communicationofdream.adapters.WishAdapter
import com.example.b2110941_communicationofdream.databinding.FragmentWishListBinding
import com.example.b2110941_communicationofdream.models.RequestDeleteWish
import com.example.b2110941_communicationofdream.models.Wish
import com.example.b2110941_communicationofdream.sharepreferences.AppSharedPreferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class WishListFragment : Fragment(){
private lateinit var binding: FragmentWishListBinding
private lateinit var mWishList: ArrayList<Wish>
private lateinit var mWishAdapter:WishAdapter
private lateinit var mAppSharedPreferences: AppSharedPreferences
private var idUser = ""
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentWishListBinding.inflate(layoutInflater,container,false)
mAppSharedPreferences = AppSharedPreferences(requireActivity())
idUser = mAppSharedPreferences.getIdUser("idUser").toString()
//Init mWishList
mWishList = ArrayList()
//Call Api - getWishList()
getWishList()
binding.btnAdd.setOnClickListener{
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout,AddFragment())
.commit()
}
return binding.root
}
private fun getWishList(){
binding.progressBar.visibility = View.VISIBLE
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main){
val response = Constants.getInstance().getWishList().body()
if (response != null){
mWishList.addAll(response)
initAdapterAndSetLayout()
}
}
}
}
private fun initAdapterAndSetLayout(){
if (context == null){
return
}
mWishAdapter = WishAdapter(requireActivity(), mWishList, mAppSharedPreferences,
object : WishAdapter.IClickItemWish{
override fun onClickUpdate(iWish: String, fullName: String, content: String) {
mAppSharedPreferences.pushWish("idWish", iWish)
mAppSharedPreferences.pushWish("fullname",fullName)
mAppSharedPreferences.pushWish("content", content)
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout,UpdateFragment()).commit()
}
override fun onClickRemove(idWish: String) {
deleteWish(idWish)
}
})
binding.rcvWishList.adapter = mWishAdapter
binding.rcvWishList.layoutManager = LinearLayoutManager(requireActivity())
binding.progressBar.visibility = View.GONE
}
private fun deleteWish(idWish:String){
binding.progressBar.visibility = View.VISIBLE
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main){
val response = Constants.getInstance()
.deleteWish(RequestDeleteWish(idUser,idWish)).body()
if (response!=null){
if (response.success){
binding.progressBar.visibility = View.GONE
Toast.makeText(requireContext(), response.message, Toast.LENGTH_SHORT).show()
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout, WishListFragment())
.commit()
}
}
}
}
}
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/fragments/WishListFragment.kt | 1976253703 |
package com.example.b2110941_communicationofdream.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.b2110941_communicationofdream.R
import com.example.b2110941_communicationofdream.apis.Constants
import com.example.b2110941_communicationofdream.databinding.FragmentRegisterBinding
import com.example.b2110941_communicationofdream.models.RequestRegisterOrLogin
import com.example.b2110941_communicationofdream.sharepreferences.AppSharedPreferences
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class RegisterFragment : Fragment() {
lateinit var binding: FragmentRegisterBinding
lateinit var mAppSharedPreferences: AppSharedPreferences
private var userName = ""
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentRegisterBinding.inflate(layoutInflater,container,false)
mAppSharedPreferences = AppSharedPreferences(requireContext())
binding.apply {
btnSignup.setOnClickListener {
if (etUsername.text.isNotEmpty()){
userName = etUsername.text.toString().trim()
//Thực hiện call api đăng kí tài khoản
registerUser(userName)
}else{
Snackbar.make(it,"Vui lòng nhập mã số sinh viên!!", Snackbar.LENGTH_LONG).show()
}
}
tvLogin.setOnClickListener {
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout,LoginFragment())
.commit()
}
}
return binding.root
}
private fun registerUser(username:String){
binding.apply {
progressBar.visibility = View.VISIBLE
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main){
val response = Constants.getInstance()
.registerUser(RequestRegisterOrLogin(username))
.body()
if(response != null){
if(response.success){
mAppSharedPreferences.putIdUser("idUser", response.idUser!!)
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout,WishListFragment()).commit()
progressBar.visibility = View.GONE
}
else
{
tvMessage.text = response.message
tvMessage.visibility = View.VISIBLE
progressBar.visibility = View.GONE
}
}
}
}
}
}
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/fragments/RegisterFragment.kt | 2962888786 |
package com.example.b2110941_communicationofdream.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.example.b2110941_communicationofdream.R
import com.example.b2110941_communicationofdream.databinding.FragmentAddBinding
import com.example.b2110941_communicationofdream.sharepreferences.AppSharedPreferences
import com.example.b2110941_communicationofdream.apis.Constants
import com.example.b2110941_communicationofdream.models.RequestAddWish
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class AddFragment : Fragment() {
private lateinit var binding:FragmentAddBinding
private lateinit var mAppSharedPreferences: AppSharedPreferences
private var idUser = ""
private var fullName = ""
private var content = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAddBinding.inflate(layoutInflater,container,false)
mAppSharedPreferences = AppSharedPreferences(requireActivity())
idUser = mAppSharedPreferences.getIdUser("idUser").toString()
binding.apply {
btnSave.setOnClickListener {
if (edtFullName.text.isNotEmpty() && edtContent.text.isNotEmpty()){
fullName = edtFullName.text.toString().trim()
content = edtContent.text.toString().trim()
addWish(fullName,content)
}
}
}
return binding.root
}
private fun addWish(fullname:String, content:String){
binding.progressBar.visibility = View.VISIBLE
CoroutineScope(Dispatchers.IO).launch {
withContext(Dispatchers.Main){
val response = Constants.getInstance()
.addWish(RequestAddWish(idUser,fullname,content)).body()
if (response != null){
if (response.success){
binding.progressBar.visibility = View.VISIBLE
Toast.makeText(requireContext(),response.message,Toast.LENGTH_SHORT).show()
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout,WishListFragment())
.commit()
}
else{
binding.progressBar.visibility = View.GONE
//Them dieu uoc khong thanh cong
Toast.makeText(requireContext(), response.message,Toast.LENGTH_SHORT).show()
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout, LoginFragment())
.commit()
}
}
}
}
}
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/fragments/AddFragment.kt | 917485923 |
package com.example.b2110941_communicationofdream.models
data class ResponseMessage(
val success: Boolean,
val message: String
)
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/ResponseMessage.kt | 719926978 |
package com.example.b2110941_communicationofdream.models
data class RequestRegisterOrLogin(
val username: String
)
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/RequestRegisterOrLogin.kt | 3446513630 |
package com.example.b2110941_communicationofdream.models
data class UserResponse(
val success: Boolean,
val message: String,
val idUser: String?
)
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/UserResponse.kt | 2129608277 |
package com.example.b2110941_communicationofdream.models
import com.google.gson.annotations.SerializedName
class RequestAddWish (
val idUser: String,
@SerializedName("name")
val fullName: String,
val content: String
) | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/RequestAddWish.kt | 3224094764 |
package com.example.b2110941_communicationofdream.models
import com.google.gson.annotations.SerializedName
data class Wish(
@SerializedName("_id")
val _id: String,
@SerializedName("name")
val name: String,
@SerializedName("owner")
val owner: User,
@SerializedName("content")
val content: String
)
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/Wish.kt | 3559952636 |
package com.example.b2110941_communicationofdream.models
import com.google.gson.annotations.SerializedName
data class User(
@SerializedName("_id")
val _id: String,
@SerializedName("username")
val username: String,
@SerializedName("avatar")
val avatar: String,
)
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/User.kt | 2727201746 |
package com.example.b2110941_communicationofdream.models
import com.google.gson.annotations.SerializedName
data class RequestUpdateWish(
val idUser: String,
val idWish: String,
@SerializedName("name")
val fullName: String,
val content: String
)
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/RequestUpdateWish.kt | 98781627 |
package com.example.b2110941_communicationofdream.models
data class RequestDeleteWish(
val idUser: String,
val idWish: String
)
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/models/RequestDeleteWish.kt | 2686117807 |
package com.example.b2110941_communicationofdream.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.b2110941_communicationofdream.R
import com.example.b2110941_communicationofdream.databinding.ItemWishBinding
import com.example.b2110941_communicationofdream.models.Wish
import com.example.b2110941_communicationofdream.sharepreferences.AppSharedPreferences
class WishAdapter (
private val context: Context,
private val wishList: List<Wish>,
private val appSharedPreferences: AppSharedPreferences,
//Truyền interface từ bên ngoài vào
private val iClickItemWish: IClickItemWish,
): RecyclerView.Adapter<WishAdapter.WishViewHolder>(){
class WishViewHolder(val binding: ItemWishBinding):RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WishViewHolder {
return WishViewHolder(ItemWishBinding
.inflate(LayoutInflater.from(parent.context),parent,false))
}
override fun getItemCount(): Int {
return wishList.size
}
override fun onBindViewHolder(holder: WishViewHolder, position: Int) {
val wish: Wish = wishList[position]
holder.binding.tvName.text = wish.name
holder.binding.tvContent.text = wish.content
Glide.with(context).load(wish.owner.avatar)
.error(R.drawable.avt_default).into(holder.binding.imgAvatar)
//Neu ng dung post uoc mo thi co quyen sua va xoa uoc mo
if(appSharedPreferences.getIdUser("idUser").toString() == wish.owner._id){
holder.binding.imgUpdate.visibility = View.VISIBLE
holder.binding.imgDelete.visibility = View.VISIBLE
}
//Bat su kien
holder.binding.imgDelete.setOnClickListener {
iClickItemWish.onClickRemove(wish._id)
}
holder.binding.imgUpdate.setOnClickListener {
iClickItemWish.onClickUpdate(wish._id, wish.name, wish.content)
}
}
interface IClickItemWish{
fun onClickUpdate(iWish: String, fullName: String, content: String)
fun onClickRemove(iWish: String)
}
}
| Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/adapters/WishAdapter.kt | 1596910285 |
package com.example.b2110941_communicationofdream.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.b2110941_communicationofdream.R
import com.example.b2110941_communicationofdream.databinding.ActivityMainBinding
import com.example.b2110941_communicationofdream.fragments.LoginFragment
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
supportFragmentManager.beginTransaction()
.replace(R.id.frame_layout,LoginFragment())
.commit()
}
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/activities/MainActivity.kt | 1000819656 |
package com.example.b2110941_communicationofdream.sharepreferences
import android.content.Context
import android.content.SharedPreferences
class AppSharedPreferences(val context: Context) {
fun putIdUser(key: String, value: String){
val sharedPreferences: SharedPreferences = context.getSharedPreferences("BEST_WISHES",0)
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString(key, value)
editor.apply()
}
fun getIdUser(key: String):String? {
val sharedPreferences: SharedPreferences = context.getSharedPreferences("BEST_WISHES",0)
return sharedPreferences.getString(key,"")
}
fun pushWish(key: String, value: String){
val sharedPreferences: SharedPreferences = context.getSharedPreferences("BEST_WISHES", 0)
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString(key, value)
editor.apply()
}
fun getWish(key: String): String?{
val sharedPreferences:SharedPreferences = context.getSharedPreferences("BEST_WISHES", 0)
return sharedPreferences.getString(key,"")
}
} | Dream_Socialize/app/src/main/java/com/example/b2110941_communicationofdream/sharepreferences/AppSharedPreferences.kt | 847932579 |
package com.example.ex1
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("com.example.ex1", appContext.packageName)
}
} | MAD-EXP1/Exp 1/app/src/androidTest/java/com/example/ex1/ExampleInstrumentedTest.kt | 319972589 |
package com.example.ex1
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)
}
} | MAD-EXP1/Exp 1/app/src/test/java/com/example/ex1/ExampleUnitTest.kt | 776494845 |
package com.example.ex1
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Layout
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var tv1 :TextView = findViewById(R.id.text1);
var btn1 :Button = findViewById(R.id.bt1);
var btn2 :Button = findViewById(R.id.btn2);
var btn3 :Button = findViewById(R.id.btn3) ;
var bg :LinearLayout =findViewById(R.id.bg);
var size=10f;
var textCol:Int =0;
var bgCol:Int =0;
btn1.setOnClickListener {
tv1.setTextSize(size);
size=size+5;
}
btn2.setOnClickListener {
when(textCol%3){
0->tv1.setTextColor(Color.RED);
1->tv1.setTextColor(Color.GREEN);
2->tv1.setTextColor(Color.BLUE);
}
textCol=textCol+1;
}
btn3.setOnClickListener {
when(bgCol%3){
0->bg.setBackgroundColor(Color.RED);
1->bg.setBackgroundColor(Color.GREEN)
2->bg.setBackgroundColor(Color.BLUE)
}
bgCol=bgCol+1;
}
}
} | MAD-EXP1/Exp 1/app/src/main/java/com/example/ex1/MainActivity.kt | 243729912 |
package com.nadaalshaibani.islamicloanform
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("com.nadaalshaibani.islamicloanform", appContext.packageName)
}
} | IslamicLoanApp/app/src/androidTest/java/com/nadaalshaibani/islamicloanform/ExampleInstrumentedTest.kt | 2759849375 |
package com.nadaalshaibani.islamicloanform
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)
}
} | IslamicLoanApp/app/src/test/java/com/nadaalshaibani/islamicloanform/ExampleUnitTest.kt | 452879308 |
package com.nadaalshaibani.islamicloanform.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import kotlin.reflect.KProperty
class LoanViewModel : ViewModel(){
var loanAmount by mutableStateOf(0.0)
private set
var periodInMonths by mutableStateOf(0)
private set
var monthlyInstallment by mutableStateOf(0.0)
private set
fun onLoanAmountChange(newLoanAmount: Double){
loanAmount = newLoanAmount
}
fun onPeriodInMonths(newPeriodInMonths: Int){
periodInMonths = newPeriodInMonths
}
fun calculateMonthlyInstallment(){
monthlyInstallment = loanAmount / periodInMonths
}
}
| IslamicLoanApp/app/src/main/java/com/nadaalshaibani/islamicloanform/viewmodel/LoanViewModel.kt | 402497381 |
package com.nadaalshaibani.islamicloanform.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | IslamicLoanApp/app/src/main/java/com/nadaalshaibani/islamicloanform/ui/theme/Color.kt | 3315368350 |
package com.nadaalshaibani.islamicloanform.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun IslamicLoanFormTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | IslamicLoanApp/app/src/main/java/com/nadaalshaibani/islamicloanform/ui/theme/Theme.kt | 943903878 |
package com.nadaalshaibani.islamicloanform.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | IslamicLoanApp/app/src/main/java/com/nadaalshaibani/islamicloanform/ui/theme/Type.kt | 3226169481 |
package com.nadaalshaibani.islamicloanform
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.nadaalshaibani.islamicloanform.composables.IslamicLoanCalculator
import com.nadaalshaibani.islamicloanform.ui.theme.IslamicLoanFormTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
IslamicLoanFormTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
IslamicLoanCalculator()
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
IslamicLoanFormTheme {
Greeting("Android")
}
} | IslamicLoanApp/app/src/main/java/com/nadaalshaibani/islamicloanform/MainActivity.kt | 2214151041 |
package com.nadaalshaibani.islamicloanform.composables
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.text.input.KeyboardType
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.nadaalshaibani.islamicloanform.viewmodel.LoanViewModel
@Composable
fun IslamicLoanCalculator(viewModel: LoanViewModel = viewModel()) {
Column {
OutlinedTextField(
value = viewModel.loanAmount.toString(),
onValueChange = { viewModel.onLoanAmountChange(it.toDouble())},
label = {Text(text = "Loan Amount")},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
OutlinedTextField(
value = viewModel.periodInMonths.toString(),
onValueChange = { viewModel.onPeriodInMonths(it.toInt()) },
label = {Text(text = "Loan Period in Months ")},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
Button(onClick = { viewModel.calculateMonthlyInstallment() }) {
Text(text = "Calculate")
}
Text(text = "Monthly Installment: ${viewModel.monthlyInstallment} KD",
style = MaterialTheme.typography.bodyMedium)
}
}
| IslamicLoanApp/app/src/main/java/com/nadaalshaibani/islamicloanform/composables/loanfunctions.kt | 3047684134 |
package com.example.movimientos_bancarios
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("com.example.movimientos_bancarios", appContext.packageName)
}
} | MOVIMIENTOS-BANCARIOS-SERGIO-REJAS/app/src/androidTest/java/com/example/movimientos_bancarios/ExampleInstrumentedTest.kt | 1475474068 |
package com.example.movimientos_bancarios
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)
}
} | MOVIMIENTOS-BANCARIOS-SERGIO-REJAS/app/src/test/java/com/example/movimientos_bancarios/ExampleUnitTest.kt | 2978749200 |
package com.example.movimientos_bancarios
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
data class Movimiento(val id: Int, val cantidad: Double, val fecha: String, val tipo: String)
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var movimientosAdapter: MovimientosAdapter
private lateinit var movimientosList: MutableList<Movimiento>
private lateinit var balanceTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// INICIALIZO MOVIMIENTOS CON DB
val dbHelper = MovimientosDatabaseHelper(this)
movimientosList = dbHelper.getAllMovimientos()
// CONFIGURO RecyclerView
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
movimientosAdapter = MovimientosAdapter(movimientosList)
recyclerView.adapter = movimientosAdapter
// MUESTRO TOAST SI LISTA ESTA VACIA
if (movimientosList.isEmpty()) {
Toast.makeText(this, "No existen registros", Toast.LENGTH_SHORT).show()
}
// BOTON PARA AGREGAR MOVIMIENTO
val addMovimientoButton: Button = findViewById(R.id.addMovimientoButton)
addMovimientoButton.setOnClickListener {
val intent = Intent(this, NuevoMovimientoActivity::class.java)
startActivity(intent)
}
// Inicializar TextView para mostrar el balance
balanceTextView = findViewById(R.id.balanceTextView)
// Obtener el balance total de la base de datos
val balance = calcularBalanceTotal(movimientosList)
// Mostrar el balance en el TextView
balanceTextView.text = getString(R.string.balance_text, balance)
}
private fun calcularBalanceTotal(movimientos: List<Movimiento>): Double {
var balance = 0.0
for (movimiento in movimientos) {
if (movimiento.tipo == "Ingreso") {
balance += movimiento.cantidad
} else if (movimiento.tipo == "Egreso") {
balance -= movimiento.cantidad
}
}
return balance
}
//ACTUALIZO RECICLERVIEW
override fun onResume() {
super.onResume()
// RECARGO LISTA
val dbHelper = MovimientosDatabaseHelper(this)
movimientosList.clear()
movimientosList.addAll(dbHelper.getAllMovimientos())
movimientosAdapter.notifyDataSetChanged()
}
// MovimientosAdapter
inner class MovimientosAdapter(private val movimientosList: List<Movimiento>) :
RecyclerView.Adapter<MovimientosAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_movimiento, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val movimiento = movimientosList[position]
holder.bind(movimiento)
}
override fun getItemCount(): Int {
return movimientosList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val cantidadTextView: TextView = itemView.findViewById(R.id.cantidadTextView)
private val fechaTextView: TextView = itemView.findViewById(R.id.fechaTextView)
fun bind(movimiento: Movimiento) {
val formattedCantidad = if (movimiento.tipo == "Ingreso") "+${movimiento.cantidad} Bs." else "-${movimiento.cantidad} Bs."
cantidadTextView.text = formattedCantidad
val colorResId = if (movimiento.tipo == "Ingreso") R.color.green else R.color.red
cantidadTextView.setTextColor(ContextCompat.getColor(itemView.context, colorResId))
fechaTextView.text = movimiento.fecha
}
}
}
}
| MOVIMIENTOS-BANCARIOS-SERGIO-REJAS/app/src/main/java/com/example/movimientos_bancarios/MainActivity.kt | 3625943835 |
package com.example.movimientos_bancarios
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.movimientos_bancarios.databinding.FragmentFirstBinding
/**
* A simple [Fragment] subclass as the default destination in the navigation.
*/
class FirstFragment : Fragment() {
private var _binding: FragmentFirstBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentFirstBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonFirst.setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | MOVIMIENTOS-BANCARIOS-SERGIO-REJAS/app/src/main/java/com/example/movimientos_bancarios/FirstFragment.kt | 2619047411 |
package com.example.movimientos_bancarios
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.movimientos_bancarios.databinding.FragmentSecondBinding
/**
* A simple [Fragment] subclass as the second destination in the navigation.
*/
class SecondFragment : Fragment() {
private var _binding: FragmentSecondBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentSecondBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonSecond.setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | MOVIMIENTOS-BANCARIOS-SERGIO-REJAS/app/src/main/java/com/example/movimientos_bancarios/SecondFragment.kt | 3554820150 |
package com.example.movimientos_bancarios
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import java.util.*
class MovimientosDatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
const val DATABASE_VERSION = 1
const val DATABASE_NAME = "movimientos.db"
const val TABLE_NAME = "movimientos"
const val COLUMN_ID = "id"
const val COLUMN_CANTIDAD = "cantidad"
const val COLUMN_FECHA = "fecha"
const val COLUMN_TIPO = "tipo"
}
override fun onCreate(db: SQLiteDatabase?) {
val createTableQuery = "CREATE TABLE $TABLE_NAME (" +
"$COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"$COLUMN_CANTIDAD REAL, " +
"$COLUMN_FECHA TEXT, " +
"$COLUMN_TIPO TEXT)"
db?.execSQL(createTableQuery)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
onCreate(db)
}
//GuARDAMOS MOVIMIENTO
fun insertMovimiento(cantidad: Double, fecha: String, tipo: String): Long {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(COLUMN_CANTIDAD, cantidad)
contentValues.put(COLUMN_FECHA, fecha)
contentValues.put(COLUMN_TIPO, tipo)
return db.insert(TABLE_NAME, null, contentValues)
}
//CONSULTO MOVIMIENTOS
fun getAllMovimientos(): MutableList<Movimiento> {
val movimientosList: MutableList<Movimiento> = mutableListOf()
val db = this.readableDatabase
val query = "SELECT * FROM $TABLE_NAME ORDER BY $COLUMN_FECHA DESC"
val cursor = db.rawQuery(query, null)
cursor?.use {
while (it.moveToNext()) {
val id = it.getInt(it.getColumnIndex(COLUMN_ID))
val cantidad = it.getDouble(it.getColumnIndex(COLUMN_CANTIDAD))
val fecha = it.getString(it.getColumnIndex(COLUMN_FECHA))
val tipo = it.getString(it.getColumnIndex(COLUMN_TIPO))
movimientosList.add(Movimiento(id, cantidad, fecha, tipo))
}
}
cursor?.close()
db.close()
return movimientosList
}
//BALANCE
fun getBalance(): Double {
val db = this.readableDatabase
var balance = 0.0
val query = "SELECT SUM($COLUMN_CANTIDAD) FROM $TABLE_NAME"
val cursor = db.rawQuery(query, null)
if (cursor.moveToFirst()) {
balance = cursor.getDouble(0)
}
cursor.close()
return balance
}
}
| MOVIMIENTOS-BANCARIOS-SERGIO-REJAS/app/src/main/java/com/example/movimientos_bancarios/MovimientosDatabaseHelper.kt | 4021471241 |
package com.example.movimientos_bancarios
import android.app.DatePickerDialog
import android.content.Intent
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.DatePicker
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.*
class NuevoMovimientoActivity : AppCompatActivity() {
private lateinit var cantidadEditText: EditText
private lateinit var fechaEditText: EditText
private lateinit var tipoSpinner: androidx.appcompat.widget.AppCompatSpinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nuevo_movimiento)
cantidadEditText = findViewById(R.id.cantidadEditText)
fechaEditText = findViewById(R.id.fechaEditText)
tipoSpinner = findViewById(R.id.tipoSpinner)
// configuro Spinner con opciones de tipo de movimiento
val tiposMovimiento = arrayOf("Ingreso", "Egreso")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, tiposMovimiento)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
tipoSpinner.adapter = adapter
// configuro EditText para DatePicker
fechaEditText.setOnClickListener {
mostrarDatePicker()
}
// configuro el botón de guardar
val guardarButton: Button = findViewById(R.id.guardarButton)
guardarButton.setOnClickListener {
guardarMovimiento()
}
}
private fun mostrarDatePicker() {
// obtengo la fecha actual
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
// Crea el DatePickerDialog
val datePickerDialog = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { view: DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int ->
val selectedDate = Calendar.getInstance()
selectedDate.set(year, monthOfYear, dayOfMonth)
// formateo la fecha seleccionada y defino EditText
val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val formattedDate = sdf.format(selectedDate.time)
fechaEditText.setText(formattedDate)
},
year,
month,
day
)
// muestro el DatePickerDialog
datePickerDialog.show()
}
private fun guardarMovimiento() {
// obtengo los valores ingresados por el usuario
val cantidad = cantidadEditText.text.toString().toDoubleOrNull()
val fecha = fechaEditText.text.toString()
val tipo = tipoSpinner.selectedItem.toString()
// Verifico si se ingresaron todos los campos
if (cantidad != null && fecha.isNotEmpty() && tipo.isNotEmpty()) {
// guardamos el movimiento en la base de datos
val dbHelper = MovimientosDatabaseHelper(this)
val id = dbHelper.insertMovimiento(cantidad, fecha, tipo)
// Verifica si la inserción fue exitosa
if (id != -1L) {
// Muestra mensaje
Toast.makeText(this, "Movimiento guardado correctamente", Toast.LENGTH_SHORT).show()
// Lleva al usuario a MainActivity
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
} else {
// mensaje de error insert falla
Toast.makeText(this, "Error al guardar el movimiento", Toast.LENGTH_SHORT).show()
}
} else {
// mensaje de error campos vacios
Toast.makeText(this, "Debes completar todos los campos", Toast.LENGTH_SHORT).show()
}
}
}
| MOVIMIENTOS-BANCARIOS-SERGIO-REJAS/app/src/main/java/com/example/movimientos_bancarios/NuevoMovimientoActivity.kt | 1097685610 |
import com.wah.kr2.DockPoolLock
import com.wah.kr2.LOG_FILE_NAME
import com.wah.kr2.ShipThread
import java.io.File
fun main() {
Thread.currentThread().contextClassLoader.loadClass("com.wah.kr2.DockPoolSynchronized")
val dockPool = DockPoolLock
for (i in 0 until 100) {
ShipThread(i, dockPool).start()
}
File(LOG_FILE_NAME).writeBytes("".toByteArray())
for (j in 0 .. 5) {
dockPool.logState()
Thread.sleep(5000)
}
} | web_sem7_kr2/src/main/kotlin/Main.kt | 2624918202 |
package com.wah.kr2
const val LOG_FILE_NAME = "C:/logs.txt"
/**
* This interface represents dock pool
*/
interface DockPool {
/**
* Retrieves dock from pool
* @return dock
*/
fun giveDock(): Dock
/**
* Returns dock to pool
*/
fun returnDock(dock: Dock)
/**
* Logs port state
*/
fun logState()
} | web_sem7_kr2/src/main/kotlin/com/wah/kr2/DockPool.kt | 2075288046 |
package com.wah.kr2
import java.io.File
import java.time.Instant
import java.util.concurrent.locks.ReentrantLock
import kotlin.collections.ArrayDeque
private const val DOCKS_AMOUNT = 10
/**
* This object represents lock implementation of [DockPool]
*/
object DockPoolLock: DockPool {
private val availableDocs = ArrayDeque<Dock>()
private val retrievedDocs = ArrayDeque<Dock>()
private val lock = ReentrantLock()
private val condition = lock.newCondition()
init {
for (i in 0 until DOCKS_AMOUNT) {
availableDocs.add(Dock(i))
}
}
/**
* Retrieves dock if available, waits for available dock otherwise
* @return dock
*/
override fun giveDock(): Dock {
lock.lock()
while (availableDocs.isEmpty()) {
condition.await()
}
return availableDocs.removeLast().also {
retrievedDocs.add(it)
lock.unlock()
}
}
/**
* Returns dock to pool
*/
override fun returnDock(dock: Dock) {
lock.lock()
availableDocs.add(dock)
retrievedDocs.remove(dock)
condition.signal()
lock.unlock()
}
/**
* Logs port state
*/
override fun logState() {
lock.lock()
val stringBuilder = StringBuilder()
stringBuilder.append("Timestamp: ").append(Instant.now()).append("\n")
stringBuilder.append("Port state:\n")
availableDocs.forEach {
stringBuilder.append("Dock ").append(it.id).append(" state ").append(it.state).append("\n")
}
retrievedDocs.forEach {
stringBuilder.append("Dock ").append(it.id).append(" state ").append(it.state).append("\n")
}
lock.unlock()
File(LOG_FILE_NAME).appendBytes(stringBuilder.toString().toByteArray())
}
} | web_sem7_kr2/src/main/kotlin/com/wah/kr2/DockPoolLock.kt | 55713691 |
package com.wah.kr2
enum class DockState {
AVAILABLE, BUSY, LOADING, UNLOADING
} | web_sem7_kr2/src/main/kotlin/com/wah/kr2/DockState.kt | 1246879529 |
package com.wah.kr2
/**
* This class represents Dock
* @property id dock id
*/
class Dock(val id: Int) {
var state = DockState.AVAILABLE
private set
/**
* Loads cargo
*/
fun loadCargo() {
state = DockState.LOADING
Thread.sleep(1000)
state = DockState.AVAILABLE
}
/**
* Unloads cargo
*/
fun unloadCargo() {
state = DockState.UNLOADING
Thread.sleep(1000)
state = DockState.BUSY
}
} | web_sem7_kr2/src/main/kotlin/com/wah/kr2/Dock.kt | 3178083343 |
package com.wah.kr2
import java.time.Instant
/**
* This class represents ship thread
* @property id thread id
* @property dockPool poolProvider
*
*/
class ShipThread(private val id: Int, private val dockPool: DockPool): Thread() {
override fun run() {
val dock = dockPool.giveDock()
println("Ship $id unloading cargo in dock ${dock.id}. Timestamp: ${Instant.now()}")
dock.unloadCargo()
println("Ship $id unloaded cargo in dock ${dock.id}. Timestamp: ${Instant.now()}")
println("Ship $id loading cargo in dock ${dock.id}. Timestamp: ${Instant.now()}")
dock.loadCargo()
println("Ship $id loaded cargo in dock ${dock.id}. Timestamp: ${Instant.now()}")
dockPool.returnDock(dock)
}
}
| web_sem7_kr2/src/main/kotlin/com/wah/kr2/ShipThread.kt | 549815079 |
package com.firstproject02
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "FirstProject02"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
| reactNative-helloWorld/android/app/src/main/java/com/firstproject02/MainActivity.kt | 4212580409 |
package com.firstproject02
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
}
| reactNative-helloWorld/android/app/src/main/java/com/firstproject02/MainApplication.kt | 1926700712 |
package dev.hasali.luna
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("dev.hasali.luna", appContext.packageName)
}
} | luna/app/src/androidTest/java/dev/hasali/luna/ExampleInstrumentedTest.kt | 2930548758 |
package dev.hasali.luna
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)
}
} | luna/app/src/test/java/dev/hasali/luna/ExampleUnitTest.kt | 4147401620 |
package dev.hasali.luna.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | luna/app/src/main/java/dev/hasali/luna/ui/theme/Color.kt | 955847518 |
package dev.hasali.luna.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun LunaTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
| luna/app/src/main/java/dev/hasali/luna/ui/theme/Theme.kt | 2846119892 |
package dev.hasali.luna.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | luna/app/src/main/java/dev/hasali/luna/ui/theme/Type.kt | 1051095600 |
package dev.hasali.luna
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import dev.hasali.luna.data.LunaDatabase
import dev.hasali.luna.ui.theme.LunaTheme
import io.ktor.client.HttpClient
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.observer.ResponseObserver
import io.ktor.client.statement.request
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.serialization.kotlinx.serialization
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import logcat.logcat
import java.time.Duration
@OptIn(ExperimentalSerializationApi::class)
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestNotificationPermissions()
WorkManager.getInstance(applicationContext)
.enqueueUniquePeriodicWork(
"background_updates_check",
ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequestBuilder<BackgroundUpdatesWorker>(Duration.ofHours(1))
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresBatteryNotLow(true)
.build()
)
.build()
)
val client = HttpClient {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
explicitNulls = false
})
serialization(ContentType.Application.OctetStream, Json {
ignoreUnknownKeys = true
explicitNulls = false
})
}
ResponseObserver {
logcat { "method=${it.request.method}, url=${it.request.url}, status=${it.status}" }
}
}
val db = LunaDatabase.open(this)
setContent {
LunaTheme {
Surface {
App(client, db)
}
}
}
}
private fun requestNotificationPermissions() {
val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (!isGranted) {
Toast.makeText(
this,
"Notifications will not be received when apps are updated",
Toast.LENGTH_SHORT
).show()
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ContextCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
@Composable
private fun App(client: HttpClient, db: LunaDatabase) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "apps_list") {
composable("apps_list") {
AppsListPage(
viewModel = viewModel {
AppsListViewModel(
application = application,
client = client,
db = db,
)
},
onAddApp = { navController.navigate("add_app") },
)
}
composable(
"add_app",
enterTransition = {
fadeIn() + slideIntoContainer(towards = AnimatedContentTransitionScope.SlideDirection.Start)
},
exitTransition = {
fadeOut() + slideOutOfContainer(towards = AnimatedContentTransitionScope.SlideDirection.End)
}
) {
AddAppPage(client = client, db = db)
}
}
}
}
| luna/app/src/main/java/dev/hasali/luna/MainActivity.kt | 750520380 |
package dev.hasali.luna
import android.content.Context
import androidx.core.app.NotificationChannelCompat
import androidx.core.app.NotificationManagerCompat
object NotificationChannels {
const val APP_UPDATES = "app_updates"
fun createAll(context: Context) {
createUpdateNotificationChannel(context)
}
private fun createUpdateNotificationChannel(context: Context) {
val channel =
NotificationChannelCompat.Builder(APP_UPDATES, NotificationManagerCompat.IMPORTANCE_LOW)
.setName("App updates")
.setShowBadge(true)
.build()
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.createNotificationChannel(channel)
}
}
| luna/app/src/main/java/dev/hasali/luna/NotificationChannels.kt | 1978884051 |
package dev.hasali.luna
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build
import logcat.logcat
class InstallReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val status = intent.getIntExtra(
PackageInstaller.EXTRA_STATUS, -123 // -1 is used by STATUS_PENDING_USER_ACTION
)
val sessionId = intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1)
val packageName = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME)
logcat { "Got status $status, packageName=$packageName, sessionId=$sessionId" }
when (status) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val application = context.applicationContext as LunaApplication
if (application.isInBackground) {
PendingAppInstalls.notifyFailed(
sessionId,
PackageInstaller.STATUS_PENDING_USER_ACTION,
"User action required, but app is in background"
)
} else {
val activityIntent =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra(Intent.EXTRA_INTENT)
}
if (activityIntent != null) {
context.startActivity(activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
PackageInstaller.STATUS_SUCCESS -> {
logcat { "Package installation succeeded for $packageName" }
PendingAppInstalls.notifySucceeded(sessionId)
}
else -> {
val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
logcat { "Package installation failed for $packageName, msg=$message" }
PendingAppInstalls.notifyFailed(sessionId, status, message)
}
}
}
}
| luna/app/src/main/java/dev/hasali/luna/InstallReceiver.kt | 2386185704 |
package dev.hasali.luna
import android.content.pm.PackageInfo
import android.os.Build
val PackageInfo.longVersionCodeCompat
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
longVersionCode
} else {
@Suppress("DEPRECATION")
versionCode.toLong()
}
| luna/app/src/main/java/dev/hasali/luna/Utils.kt | 553756856 |
package dev.hasali.luna
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import dev.hasali.luna.data.LunaDatabase
import dev.hasali.luna.ui.theme.LunaTheme
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.observer.ResponseObserver
import io.ktor.client.request.get
import io.ktor.client.statement.request
import io.ktor.http.ContentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.serialization.kotlinx.serialization
import kotlinx.coroutines.launch
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import logcat.logcat
@OptIn(ExperimentalSerializationApi::class)
class InAppUpdateActivity : ComponentActivity() {
companion object {
private const val UnknownPackageName = 1
private const val PermissionDenied = 2
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val packageName = intent.getStringExtra("packageName")
if (packageName == null) {
setResult(UnknownPackageName)
finish()
return
}
if (callingActivity?.packageName != packageName) {
setResult(PermissionDenied)
finish()
return
}
val client = HttpClient {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
explicitNulls = false
})
serialization(ContentType.Application.OctetStream, Json {
ignoreUnknownKeys = true
explicitNulls = false
})
}
ResponseObserver {
logcat { "method=${it.request.method}, url=${it.request.url}, status=${it.status}" }
}
}
val db = LunaDatabase.open(this)
val installer = AppInstaller(this)
var isInstalling by mutableStateOf(false)
var progress by mutableStateOf<AppInstaller.InstallationProgress?>(null)
var installResult by mutableStateOf<AppInstaller.InstallationResult?>(null)
setContent {
val scope = rememberCoroutineScope()
val pkg by remember { db.packageDao().getByPackageName(packageName) }
.collectAsState(initial = null)
val manifest by produceState<AppManifest?>(null, pkg) {
if (pkg != null) {
val res = client.get(pkg!!.manifestUrl)
value = res.body<AppManifest>()
}
}
LaunchedEffect(isInstalling) {
setFinishOnTouchOutside(!isInstalling)
}
LunaTheme {
Surface(
modifier = Modifier.widthIn(min = 280.dp, max = 560.dp),
shape = AlertDialogDefaults.shape,
color = AlertDialogDefaults.containerColor,
tonalElevation = AlertDialogDefaults.TonalElevation,
) {
Column(modifier = Modifier.padding(24.dp)) {
Text("Update", style = MaterialTheme.typography.headlineSmall)
Column(modifier = Modifier.padding(top = 16.dp, bottom = 24.dp)) {
if (manifest == null) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
} else {
if (installResult != null) {
installResult!!.let { installResult ->
when (installResult) {
is AppInstaller.InstallationResult.Failure -> {
Text(installResult.message ?: "Update failed")
}
AppInstaller.InstallationResult.NoCompatiblePackage -> {
Text("No compatible package found for this device")
}
AppInstaller.InstallationResult.Success -> {
Text("${manifest!!.info.name} was successfully updated")
}
AppInstaller.InstallationResult.UserCanceled -> {
Text("Update was canceled")
}
}
}
} else if (isInstalling) {
progress.let { progress ->
when (progress) {
is AppInstaller.InstallationProgress.Downloading -> {
Text("Downloading...")
Spacer(modifier = Modifier.height(8.dp))
LinearProgressIndicator(
progress.value,
modifier = Modifier.fillMaxWidth()
)
}
AppInstaller.InstallationProgress.Installing, null -> {
Text("Installing...")
Spacer(modifier = Modifier.height(8.dp))
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
}
}
} else {
Text("An update is available for ${manifest!!.info.name}")
Spacer(modifier = Modifier.height(8.dp))
Text(
"Update to ${manifest!!.info.version} (${manifest!!.info.versionCode})",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier.fillMaxWidth(),
) {
val isActionsEnabled =
manifest != null && (!isInstalling || installResult != null)
TextButton(enabled = isActionsEnabled, onClick = { finish() }) {
Text("Cancel")
}
if (installResult != null) {
TextButton(
enabled = isActionsEnabled,
onClick = {
val intent =
packageManager.getLaunchIntentForPackage(packageName)
?.apply { addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) }
if (intent != null) {
startActivity(intent)
}
finish()
},
) {
Text("Open")
}
} else {
TextButton(
enabled = isActionsEnabled,
onClick = {
isInstalling = true
scope.launch {
installResult = installer.install(manifest!!) {
progress = it
}
}
},
) {
Text("Install")
}
}
}
}
}
}
}
}
}
| luna/app/src/main/java/dev/hasali/luna/InAppUpdateActivity.kt | 4061287571 |
package dev.hasali.luna
import android.app.Application
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import fr.bipi.treessence.context.GlobalContext.startTimber
import logcat.AndroidLogcatLogger
import logcat.LogPriority
import logcat.logcat
class LunaApplication : Application() {
var isInBackground = true
private set
override fun onCreate() {
super.onCreate()
AndroidLogcatLogger.installOnDebuggableApp(this, minPriority = LogPriority.VERBOSE)
startTimber {
if (BuildConfig.DEBUG) {
debugTree()
}
fileTree {
level = Log.INFO
dir = "${cacheDir.absolutePath}/logs"
}
}
NotificationChannels.createAll(this)
ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
isInBackground = false
[email protected] { "Entered foreground" }
}
override fun onStop(owner: LifecycleOwner) {
isInBackground = true
[email protected] { "Entered background" }
}
})
}
}
| luna/app/src/main/java/dev/hasali/luna/LunaApplication.kt | 2687128272 |
package dev.hasali.luna
import android.Manifest
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import dev.hasali.luna.data.LunaDatabase
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.observer.ResponseObserver
import io.ktor.client.request.get
import io.ktor.client.statement.request
import io.ktor.http.ContentType
import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json
import io.ktor.serialization.kotlinx.serialization
import kotlinx.coroutines.flow.first
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import logcat.logcat
import timber.log.Timber
@OptIn(ExperimentalSerializationApi::class)
class BackgroundUpdatesWorker(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
private lateinit var client: HttpClient
private lateinit var db: LunaDatabase
private lateinit var installer: AppInstaller
override suspend fun doWork(): Result {
Timber.i("Starting background updates worker")
client = HttpClient {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
explicitNulls = false
})
serialization(ContentType.Application.OctetStream, Json {
ignoreUnknownKeys = true
explicitNulls = false
})
}
ResponseObserver {
[email protected] { "method=${it.request.method}, url=${it.request.url}, status=${it.status}" }
}
}
db = LunaDatabase.open(applicationContext)
installer = AppInstaller(applicationContext)
if (applicationContext.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE == 0) {
updateSelf()
}
updateInstalledPackages()
return Result.success()
}
private suspend fun updateSelf() {
val info = try {
applicationContext.packageManager.getPackageInfo("dev.hasali.luna", 0)
} catch (e: NameNotFoundException) {
return
}
val res =
client.get("https://github.com/hasali19/luna/releases/download/latest/luna.apk.json")
val manifest = if (res.status.isSuccess()) {
res.body<AppManifest>()
} else {
return
}
if (manifest.info.versionCode > info.longVersionCodeCompat) {
Timber.i("Updating luna to ${manifest.info.version}+${manifest.info.versionCode}")
installer.install(manifest)
}
}
private suspend fun updateInstalledPackages() {
val packages = db.packageDao().getAll().first()
for (pkg in packages) {
val info = try {
applicationContext.packageManager.getPackageInfo(pkg.packageName, 0)
} catch (e: NameNotFoundException) {
continue
}
val res = client.get(pkg.manifestUrl)
val manifest = if (res.status.isSuccess()) {
res.body<AppManifest>()
} else {
continue
}
db.packageDao().updateLatestVersion(
manifest.info.packageName,
manifest.info.version,
manifest.info.versionCode,
)
if (manifest.info.versionCode > info.longVersionCodeCompat) {
if (!installer.shouldSilentlyUpdatePackage(manifest.info.packageName)) {
Timber.i("Skipping background update for ${manifest.info.packageName}")
continue
}
Timber.i("Updating ${manifest.info.packageName} to ${manifest.info.version}+${manifest.info.versionCode}")
val result = installer.install(manifest)
val displayVersion = "${manifest.info.version}+${manifest.info.versionCode}"
val message = when (result) {
is AppInstaller.InstallationResult.Failure -> "Failed to update to $displayVersion"
AppInstaller.InstallationResult.NoCompatiblePackage -> "No compatible package found for version $displayVersion"
AppInstaller.InstallationResult.Success -> "App was updated to $displayVersion"
AppInstaller.InstallationResult.UserCanceled -> continue
}
val intent = Intent(applicationContext, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent = PendingIntent.getActivity(
applicationContext,
0,
intent,
PendingIntent.FLAG_IMMUTABLE
)
val notification =
NotificationCompat.Builder(applicationContext, NotificationChannels.APP_UPDATES)
.setContentTitle(manifest.info.name)
.setContentText(message)
.setSmallIcon(R.drawable.ic_notification_small)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build()
with(NotificationManagerCompat.from(applicationContext)) {
if (ContextCompat.checkSelfPermission(
applicationContext,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
) {
notify(pkg.id, notification)
}
}
}
}
}
}
| luna/app/src/main/java/dev/hasali/luna/BackgroundUpdatesWorker.kt | 819191689 |
package dev.hasali.luna
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.OutlinedIconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import dev.hasali.luna.data.LunaDatabase
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.http.isSuccess
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddAppPage(client: HttpClient, db: LunaDatabase) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val onBackPressedDispatcherOwner = LocalOnBackPressedDispatcherOwner.current
Scaffold(
topBar = {
TopAppBar(title = { Text("Add App") }, navigationIcon = {
IconButton(onClick = { onBackPressedDispatcherOwner?.onBackPressedDispatcher?.onBackPressed() }) {
Icon(Icons.Default.ArrowBack, contentDescription = null)
}
})
},
) { padding ->
Surface {
Box(
modifier = Modifier
.padding(padding)
.padding(16.dp),
) {
var manifestUrl by remember { mutableStateOf("") }
var manifest: AppManifest? by remember { mutableStateOf(null) }
Column {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = manifestUrl,
placeholder = { Text("Manifest url") },
onValueChange = { manifestUrl = it },
)
Spacer(modifier = Modifier.height(24.dp))
var loading by remember { mutableStateOf(false) }
if (loading) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.CenterHorizontally))
} else {
Button(
modifier = Modifier.align(Alignment.CenterHorizontally),
onClick = {
manifest = null
loading = true
scope.launch {
val res = client.get(manifestUrl)
if (res.status.isSuccess()) {
manifest = res.body<AppManifest>()
} else {
Toast.makeText(context, "App not found", Toast.LENGTH_SHORT)
.show()
}
loading = false
}
},
) {
Row {
Icon(
imageVector = Icons.Default.Search,
contentDescription = null,
modifier = Modifier.size(18.dp),
)
Spacer(modifier = Modifier.width(8.dp))
Text("Search")
}
}
}
manifest?.let { manifest ->
var installing by remember { mutableStateOf(false) }
var progress: Float? by remember {
mutableStateOf(
null
)
}
var isAdded: Boolean? by remember { mutableStateOf(null) }
LaunchedEffect(manifest) {
isAdded = db.packageDao().getByPackageName(manifest.info.packageName)
.firstOrNull() != null
}
Spacer(modifier = Modifier.height(32.dp))
AppDetailsCard(
manifest = manifest,
isAdded = isAdded,
installing = installing,
progress = progress,
onInstall = {
installing = true
scope.launch {
db.packageDao().insert(
dev.hasali.luna.data.Package(
label = manifest.info.name,
packageName = manifest.info.packageName,
manifestUrl = manifestUrl,
latestVersionName = manifest.info.version,
latestVersionCode = manifest.info.versionCode,
)
)
val result = AppInstaller(context).install(manifest) {
progress = when (it) {
is AppInstaller.InstallationProgress.Downloading -> it.value
AppInstaller.InstallationProgress.Installing -> 1f
}
}
if (result is AppInstaller.InstallationResult.NoCompatiblePackage) {
Toast.makeText(
context,
"No compatible package found",
Toast.LENGTH_SHORT
).show()
}
installing = false
progress = null
}
}
)
}
}
}
}
}
}
@Composable
private fun AppDetailsCard(
manifest: AppManifest,
isAdded: Boolean?,
installing: Boolean,
progress: Float?,
onInstall: () -> Unit
) {
val context = LocalContext.current
val avatar = remember {
ImageRequest.Builder(context)
.data(manifest.info.icon)
.crossfade(true)
.build()
}
ElevatedCard {
ListItem(
headlineContent = { Text(manifest.info.name) },
supportingContent = { Text(manifest.info.author) },
leadingContent = {
AsyncImage(
model = avatar,
contentDescription = null,
modifier = Modifier
.size(40.dp)
.clip(CircleShape),
)
},
trailingContent = if (isAdded == null) {
null
} else if (isAdded) ({
Text("Added")
}) else ({
OutlinedIconButton(enabled = !installing, onClick = onInstall) {
Icon(
painter = painterResource(id = R.drawable.ic_download),
contentDescription = null,
)
if (installing) {
if (progress == null) {
CircularProgressIndicator(strokeWidth = 2.dp)
} else {
CircularProgressIndicator(progress, strokeWidth = 2.dp)
}
}
}
}),
modifier = Modifier.clickable(enabled = manifest.info.url != null) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(manifest.info.url))
context.startActivity(intent)
},
)
}
}
| luna/app/src/main/java/dev/hasali/luna/AddAppPage.kt | 1023199448 |
package dev.hasali.luna
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import java.text.DateFormat
import java.util.Date
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppsListPage(
viewModel: AppsListViewModel,
onAddApp: () -> Unit,
) {
val packages by viewModel.packages.collectAsState(initial = null)
val updatablePackages by viewModel.updatablePackages.collectAsState(initial = null)
Scaffold(topBar = { TopAppBar(title = { Text("Apps") }) }, floatingActionButton = {
FloatingActionButton(onClick = onAddApp) {
Icon(Icons.Default.Add, contentDescription = null)
}
}) { padding ->
Surface {
Box(
modifier = Modifier
.padding(padding)
.fillMaxSize(),
) {
packages.let { packages ->
if (packages == null) {
CircularProgressIndicator()
} else {
LazyColumn {
item {
LunaStatusCard(
lunaPackage = viewModel.lunaPackage,
onUpdate = viewModel::updateLuna,
)
}
if (packages.isEmpty()) {
item {
Text(
text = "No apps installed",
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth(),
)
}
} else {
item {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
) {
Text("Installed", modifier = Modifier.weight(1f))
if (updatablePackages == null || updatablePackages!!.isEmpty()) {
Button(
enabled = !viewModel.isCheckingForUpdates,
onClick = viewModel::checkForUpdates,
) {
Text("Check for updates")
if (viewModel.isCheckingForUpdates) {
Spacer(modifier = Modifier.width(8.dp))
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
color = LocalContentColor.current,
strokeWidth = 2.dp,
)
}
}
} else {
Button(
enabled = !viewModel.isUpdating,
onClick = viewModel::updateAll,
) {
Text("Update all (${updatablePackages!!.size})")
if (viewModel.isUpdating) {
Spacer(modifier = Modifier.width(8.dp))
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
color = LocalContentColor.current,
strokeWidth = 2.dp,
)
}
}
}
}
}
items(packages) {
AppsListItem(
model = it,
onInstall = { viewModel.install(it) },
)
}
}
}
}
}
}
}
}
}
@Composable
private fun LunaStatusCard(lunaPackage: LunaPackageState, onUpdate: () -> Unit) {
ElevatedCard(modifier = Modifier.padding(16.dp)) {
val trailingContent: @Composable () -> Unit = if (lunaPackage.isUpdating) ({
val updateProgress = lunaPackage.updateProgress.value
if (updateProgress == null) {
CircularProgressIndicator()
} else {
CircularProgressIndicator(
updateProgress
)
}
}) else if (lunaPackage.isUpdateAvailable) ({
TextButton(onClick = onUpdate) {
Text("Update")
}
}) else ({
Text("${lunaPackage.installedVersionName}-${lunaPackage.installedVersionCode}")
})
Column {
ListItem(
headlineContent = { Text(lunaPackage.name) },
supportingContent = { Text(lunaPackage.packageName) },
leadingContent = {
AsyncImage(
model = lunaPackage.icon,
contentDescription = null,
modifier = Modifier.size(48.dp)
)
},
trailingContent = trailingContent,
)
}
}
}
@Composable
private fun AppsListItem(model: PackageModel, onInstall: () -> Unit) {
val packageInfo = model.info
val overlineContent: (@Composable () -> Unit)? = if (packageInfo == null) ({
Text("Not installed")
}) else {
null
}
val leadingContent: (@Composable () -> Unit)? = if (model.icon != null) ({
AsyncImage(
model = model.icon,
contentDescription = null,
modifier = Modifier.size(48.dp)
)
}) else {
null
}
val trailingContent: @Composable () -> Unit = if (packageInfo != null) ({
val installedVersionCode = packageInfo.longVersionCodeCompat
val latestVersionName = model.pkg.latestVersionName ?: "0.0.0"
val latestVersionCode = model.pkg.latestVersionCode ?: -1
if (latestVersionCode <= installedVersionCode) {
Column(horizontalAlignment = Alignment.End) {
Text("${packageInfo.versionName}-$installedVersionCode")
Text(DateFormat.getDateInstance().format(Date(packageInfo.lastUpdateTime)))
}
} else {
Text(
text = "${packageInfo.versionName}-$installedVersionCode ~ $latestVersionName-$latestVersionCode",
fontStyle = FontStyle.Italic,
textDecoration = TextDecoration.Underline,
)
}
}) else ({
TextButton(onClick = onInstall) {
Text("Install")
}
})
ListItem(
headlineContent = { Text(model.pkg.label) },
supportingContent = { Text(model.pkg.packageName) },
overlineContent = overlineContent,
leadingContent = leadingContent,
trailingContent = trailingContent,
)
}
| luna/app/src/main/java/dev/hasali/luna/AppsListPage.kt | 1586614489 |
package dev.hasali.luna
import android.app.Application
import android.content.pm.PackageInfo
import android.graphics.drawable.Drawable
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import dev.hasali.luna.data.LunaDatabase
import dev.hasali.luna.data.Package
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.http.isSuccess
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import logcat.logcat
data class PackageModel(
val pkg: Package,
val info: PackageInfo?,
val icon: Drawable?,
)
data class LunaPackageState(
val name: String,
val packageName: String,
val icon: Drawable,
val installedVersionName: String,
val installedVersionCode: Long,
val latestVersionName: String?,
val latestVersionCode: Long?,
val isUpdating: Boolean = false,
val updateProgress: MutableState<Float?> = mutableStateOf(null),
) {
val isUpdateAvailable
get() = latestVersionCode != null && installedVersionCode < latestVersionCode
}
class AppsListViewModel(
private val application: Application,
private val client: HttpClient,
private val db: LunaDatabase,
) : AndroidViewModel(application) {
private val _packages = MutableStateFlow<List<Package>?>(null)
private val _packageInfos = MutableStateFlow<Map<String, PackageInfo>?>(null)
var lunaPackage: LunaPackageState by mutableStateOf(getInitialLunaPackageState())
private set
val packages = combine(
_packages.filterNotNull(),
_packageInfos.filterNotNull()
) { packages, packageInfos ->
packages.map {
val info = packageInfos.get(it.packageName)
PackageModel(
it,
info,
info?.applicationInfo?.loadIcon(application.packageManager),
)
}
}
val updatablePackages
get() = combine(
_packages.filterNotNull(),
_packageInfos.filterNotNull()
) { packages, packageInfos ->
packages.filter {
val packageInfo = packageInfos[it.packageName] ?: return@filter false
val installedVersionCode = packageInfo.longVersionCodeCompat
it.latestVersionCode != null && installedVersionCode < it.latestVersionCode
}
}
private var _isCheckingForUpdates by mutableStateOf(false)
val isCheckingForUpdates @Composable get() = _isCheckingForUpdates
private var _isUpdating by mutableStateOf(false)
val isUpdating @Composable get() = _isUpdating
init {
viewModelScope.launch {
launch {
db.packageDao().getAll().collect {
_packages.value = it
}
}
launch {
_packages.filterNotNull().collect { packages ->
updatePackageInfos(packages)
}
}
launch inner@{
val lunaManifest =
getPackageManifest("https://github.com/hasali19/luna/releases/download/latest/luna.apk.json")
?: return@inner
lunaPackage = lunaPackage.copy(
latestVersionName = lunaManifest.info.version,
latestVersionCode = lunaManifest.info.versionCode,
)
}
}
}
fun refreshInstallStatuses() {
_packages.value?.let { packages -> updatePackageInfos(packages) }
}
fun checkForUpdates() {
_isCheckingForUpdates = true
viewModelScope.launch {
val packageInfos = _packageInfos.value
val packages =
_packages.value?.filter { packageInfos?.containsKey(it.packageName) ?: false }
?: return@launch
packages
.mapNotNull { pkg -> getPackageManifest(pkg.manifestUrl) }
.forEach { manifest ->
db.packageDao().updateLatestVersion(
manifest.info.packageName,
manifest.info.version,
manifest.info.versionCode,
)
}
_isCheckingForUpdates = false
}
}
fun updateLuna() {
lunaPackage = lunaPackage.copy(isUpdating = true, updateProgress = mutableStateOf(null))
viewModelScope.launch {
val manifest =
getPackageManifest("https://github.com/hasali19/luna/releases/download/latest/luna.apk.json")
?: return@launch
val result = AppInstaller(application).install(manifest) {
lunaPackage.updateProgress.value = when (it) {
is AppInstaller.InstallationProgress.Downloading -> it.value
AppInstaller.InstallationProgress.Installing -> 1f
}
}
if (result != AppInstaller.InstallationResult.Success) {
Toast.makeText(application, "Failed to update Luna", Toast.LENGTH_SHORT).show()
}
lunaPackage = lunaPackage.copy(isUpdating = false)
}
}
fun updateAll() {
_isUpdating = true
viewModelScope.launch {
for (pkg in updatablePackages.first()) {
val manifest = getPackageManifest(pkg.manifestUrl) ?: continue
when (val result = AppInstaller(application).install(manifest) {}) {
is AppInstaller.InstallationResult.Success -> {
Toast.makeText(
application,
"Package installed successfully: ${manifest.info.packageName}",
Toast.LENGTH_SHORT
).show()
}
is AppInstaller.InstallationResult.NoCompatiblePackage -> {
Toast.makeText(
application,
"No compatible package found",
Toast.LENGTH_SHORT
).show()
}
is AppInstaller.InstallationResult.UserCanceled -> {
Toast.makeText(
application,
"Installation was canceled",
Toast.LENGTH_SHORT
).show()
}
is AppInstaller.InstallationResult.Failure -> {
Toast.makeText(
application,
"Installation failed: ${result.message}",
Toast.LENGTH_SHORT
).show()
}
}
refreshInstallStatuses()
}
_isUpdating = false
}
}
fun install(pkg: PackageModel) {
viewModelScope.launch {
logcat { "Retrieving manifest for ${pkg.pkg.packageName} from ${pkg.pkg.manifestUrl}" }
val res = client.get(pkg.pkg.manifestUrl)
val manifest =
if (res.status.isSuccess()) {
res.body<AppManifest>()
} else {
Toast.makeText(
application,
"Failed to get manifest: ${pkg.pkg.label}",
Toast.LENGTH_SHORT
).show()
return@launch
}
val result = AppInstaller(application).install(manifest) { }
if (result is AppInstaller.InstallationResult.NoCompatiblePackage) {
Toast.makeText(
application,
"No compatible package found",
Toast.LENGTH_SHORT
).show()
}
refreshInstallStatuses()
}
}
private fun getInitialLunaPackageState(): LunaPackageState {
val packageInfo = application.packageManager.getPackageInfo("dev.hasali.luna", 0)
return LunaPackageState(
name = "Luna",
packageName = "dev.hasali.luna",
icon = application.packageManager.getApplicationIcon("dev.hasali.luna"),
installedVersionName = packageInfo.versionName,
installedVersionCode = packageInfo.longVersionCodeCompat,
latestVersionName = null,
latestVersionCode = null,
)
}
private fun updatePackageInfos(packages: List<Package>) {
_packageInfos.value = packages
.map {
runCatching {
application.packageManager.getPackageInfo(it.packageName, 0)
}
}
.mapNotNull { it.getOrNull() }
.associateBy { it.packageName }
}
private suspend fun getPackageManifest(url: String): AppManifest? {
val res = client.get(url)
return if (res.status.isSuccess()) {
res.body<AppManifest>()
} else {
null
}
}
}
| luna/app/src/main/java/dev/hasali/luna/AppsListViewModel.kt | 737288208 |
package dev.hasali.luna
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.withContext
import logcat.logcat
import java.net.HttpURLConnection
import java.net.URL
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class AppInstaller(private val context: Context) {
sealed interface InstallationProgress {
data class Downloading(val value: Float) : InstallationProgress
data object Installing : InstallationProgress
}
sealed interface InstallationResult {
data object Success : InstallationResult
data object NoCompatiblePackage : InstallationResult
data object UserCanceled : InstallationResult
data class Failure(val message: String?) : InstallationResult
}
suspend fun shouldSilentlyUpdatePackage(packageName: String): Boolean {
val packageInstaller = context.packageManager.packageInstaller
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
val constraints = PackageInstaller.InstallConstraints.GENTLE_UPDATE
val executor = Dispatchers.Unconfined.asExecutor()
val result =
suspendCoroutine<PackageInstaller.InstallConstraintsResult> { continuation ->
packageInstaller.checkInstallConstraints(
listOf(packageName),
constraints,
executor
) {
continuation.resume(it)
}
}
result.areAllConstraintsSatisfied()
} else {
// TODO: Figure out a way to detect if the app is currently in use, below Android 14
return true
}
}
suspend fun install(
manifest: AppManifest,
onProgress: (InstallationProgress) -> Unit = {}
): InstallationResult {
val packages = manifest.packages.associateBy { it.abi ?: "any" }
val abi = Build.SUPPORTED_ABIS.find { packages.containsKey(it) } ?: "any"
val pkg = packages[abi] ?: return InstallationResult.NoCompatiblePackage
return install(pkg.name, pkg.uri, onProgress)
}
private suspend fun install(
name: String,
url: String,
onProgress: (InstallationProgress) -> Unit
): InstallationResult {
logcat { "Beginning download of '$name' from '$url'" }
val params =
PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)
}
}
val packageInstaller = context.packageManager.packageInstaller
val sessionId = packageInstaller.createSession(params)
val session = packageInstaller.openSession(sessionId)
withContext(Dispatchers.IO) {
session.openWrite(name, 0, -1).use { output ->
val connection = (URL(url).openConnection() as HttpURLConnection)
.apply { instanceFollowRedirects = true }
logcat { "Download request returned status ${connection.responseMessage}" }
val input = connection.inputStream
val size = connection.contentLength
val buffer = ByteArray(4096)
var totalBytesRead = 0
while (true) {
val read = input.read(buffer)
if (read == -1) break
output.write(buffer, 0, read)
totalBytesRead += read
onProgress(
InstallationProgress.Downloading(
totalBytesRead.toFloat() / maxOf(
totalBytesRead.toFloat(),
size.toFloat()
)
)
)
}
session.fsync(output)
logcat { "Finished downloading '$name'" }
}
}
onProgress(InstallationProgress.Installing)
logcat { "Starting install for '$name'" }
var flags = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = flags or PendingIntent.FLAG_MUTABLE
}
val intent = Intent(context, InstallReceiver::class.java)
val pendingIntent =
PendingIntent.getBroadcast(context, 3439, intent, flags)
val receiver = pendingIntent.intentSender
logcat { "Committing install session for '$name'" }
session.commit(receiver)
session.close()
val (status, message) = PendingAppInstalls.await(sessionId)
return when (status) {
PackageInstaller.STATUS_SUCCESS -> InstallationResult.Success
PackageInstaller.STATUS_FAILURE_ABORTED -> InstallationResult.UserCanceled
else -> InstallationResult.Failure(message)
}
}
}
| luna/app/src/main/java/dev/hasali/luna/AppInstaller.kt | 1902518949 |
package dev.hasali.luna
import android.content.pm.PackageInstaller
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
object PendingAppInstalls {
private val lock = Unit
private val installStatuses = mutableMapOf<Int, Pair<Int, String?>>()
private val callbacks = mutableMapOf<Int, (Int, String?) -> Unit>()
fun notifySucceeded(id: Int) {
complete(id, PackageInstaller.STATUS_SUCCESS, null)
}
fun notifyFailed(id: Int, status: Int, message: String?) {
complete(id, status, message)
}
private fun complete(id: Int, status: Int, message: String?) {
val callback = synchronized(lock) {
val callback = callbacks.remove(id)
if (callback == null) {
installStatuses.put(id, Pair(status, message))
null
} else {
callback
}
}
if (callback != null) {
callback(status, message)
}
}
suspend fun await(id: Int): Pair<Int, String?> {
return suspendCoroutine { continuation ->
val result = synchronized(lock) {
val result = installStatuses.remove(id)
if (result == null) {
callbacks[id] = { status, msg -> continuation.resume(Pair(status, msg)) }
null
} else {
result
}
}
if (result != null) {
continuation.resume(result)
}
}
}
}
| luna/app/src/main/java/dev/hasali/luna/PendingAppInstalls.kt | 1955949269 |
package dev.hasali.luna.data
import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(
version = 2,
entities = [Package::class],
autoMigrations = [
AutoMigration(from = 1, to = 2)
],
)
abstract class LunaDatabase : RoomDatabase() {
abstract fun packageDao(): PackageDao
companion object {
fun open(context: Context): LunaDatabase {
return Room.databaseBuilder(context, LunaDatabase::class.java, "luna")
.build()
}
}
}
| luna/app/src/main/java/dev/hasali/luna/data/LunaDatabase.kt | 1440914750 |
package dev.hasali.luna.data
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(indices = [Index("packageName", unique = true)])
data class Package(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val label: String,
val packageName: String,
val manifestUrl: String,
val latestVersionName: String?,
val latestVersionCode: Long?,
)
| luna/app/src/main/java/dev/hasali/luna/data/Package.kt | 49829567 |
package dev.hasali.luna.data
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface PackageDao {
@Query("SELECT * FROM Package")
fun getAll(): Flow<List<Package>>
@Query("SELECT * FROM Package WHERE packageName = :packageName")
fun getByPackageName(packageName: String): Flow<Package>
@Insert
suspend fun insert(pkg: Package)
@Query("UPDATE Package SET latestVersionName = :versionName, latestVersionCode = :versionCode WHERE packageName = :packageName")
suspend fun updateLatestVersion(packageName: String, versionName: String, versionCode: Long)
}
| luna/app/src/main/java/dev/hasali/luna/data/PackageDao.kt | 2909927669 |
package dev.hasali.luna
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class AppManifest(
val version: Version,
val info: AppInfo,
val packages: List<Package>,
) {
@Serializable
enum class Version {
@SerialName("1")
V1
}
@Serializable
data class AppInfo(
val name: String,
val author: String,
val icon: String?,
val url: String?,
val version: String,
val versionCode: Long,
val packageName: String,
)
@Serializable
data class Package(
val name: String,
val uri: String,
val abi: String?,
)
}
| luna/app/src/main/java/dev/hasali/luna/AppManifest.kt | 1116965467 |
package ua.edu.lntu.cw_Control_Work_4
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("ua.edu.lntu.cw_Control_Work_4", appContext.packageName)
}
} | IPZ_CR_4_Kalishchuk_Stas/app/src/androidTest/java/ua/edu/lntu/cw_Control_Work_4/ExampleInstrumentedTest.kt | 3533849292 |
package ua.edu.lntu.cw_Control_Work_4
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)
}
} | IPZ_CR_4_Kalishchuk_Stas/app/src/test/java/ua/edu/lntu/cw_Control_Work_4/ExampleUnitTest.kt | 2659340326 |
package ua.edu.lntu.cw_Control_Work_4.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | IPZ_CR_4_Kalishchuk_Stas/app/src/main/java/ua/edu/lntu/cw_Control_Work_4/ui/theme/Color.kt | 4130220045 |
package ua.edu.lntu.cw_Control_Work_4.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun IPZ_CP_4Theme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | IPZ_CR_4_Kalishchuk_Stas/app/src/main/java/ua/edu/lntu/cw_Control_Work_4/ui/theme/Theme.kt | 2934280776 |
package ua.edu.lntu.cw_Control_Work_4.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | IPZ_CR_4_Kalishchuk_Stas/app/src/main/java/ua/edu/lntu/cw_Control_Work_4/ui/theme/Type.kt | 2992404686 |
package ua.edu.lntu.cw_Control_Work_4
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import kotlinx.coroutines.launch
import ua.edu.lntu.cw_Control_Work_4.ui.theme.IPZ_CP_4Theme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
IPZ_CP_4Theme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MyApp()
}
}
}
}
}
@Composable
fun Screen1(navController: NavHostController) {
Column(modifier = Modifier.fillMaxSize()) {
for (i in 1..5) {
Button(
onClick = { navController.navigate("screen2/$i") },
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Button $i")
}
}
}
}
@Composable
fun Screen2(navController: NavHostController, buttonNumber: Int) {
val scope = rememberCoroutineScope()
Column(modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center
) {
Text(
textAlign = TextAlign.Center,
text = "You pressed Button $buttonNumber",
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = { scope.launch { navController.popBackStack() } },
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Go back")
}
}
}
@Composable
fun MyApp() {
val navController = rememberNavController()
MaterialTheme {
NavHost(navController, startDestination = "screen1") {
composable("screen1") { Screen1(navController) }
composable(
route = "screen2/{buttonNumber}",
arguments = listOf(navArgument("buttonNumber") { type = NavType.IntType })
) { backStackEntry ->
val buttonNumber = backStackEntry.arguments?.getInt("buttonNumber") ?: 0
Screen2(navController, buttonNumber)
}
}
}
} | IPZ_CR_4_Kalishchuk_Stas/app/src/main/java/ua/edu/lntu/cw_Control_Work_4/MainActivity.kt | 1724314728 |
package com.example.firstcomposeproject
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("com.example.firstcomposeproject", appContext.packageName)
}
} | P0012_FirstComposeProject/app/src/androidTest/java/com/example/firstcomposeproject/ExampleInstrumentedTest.kt | 3046317457 |
package com.example.firstcomposeproject
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)
}
} | P0012_FirstComposeProject/app/src/test/java/com/example/firstcomposeproject/ExampleUnitTest.kt | 1343165770 |
package com.example.firstcomposeproject.ui.theme
import androidx.compose.ui.graphics.Color
val Black500 = Color(0xff9a9b9d)
val Black900 = Color(0xff191919)
val DarkBlue = Color(0xff4c75a3)
val DarkRed = Color(0xfffb3043) | P0012_FirstComposeProject/app/src/main/java/com/example/firstcomposeproject/ui/theme/Color.kt | 3239988685 |
package com.example.firstcomposeproject.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Color.White,
secondary = Black500,
onPrimary = Color.White,
onSecondary = Black900
)
private val LightColorScheme = lightColorScheme(
primary = Black900,
secondary = Black500,
onPrimary = Black500,
onSecondary = Color.White
)
@Composable
fun FirstComposeProjectTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | P0012_FirstComposeProject/app/src/main/java/com/example/firstcomposeproject/ui/theme/Theme.kt | 1278394451 |
package com.example.firstcomposeproject.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | P0012_FirstComposeProject/app/src/main/java/com/example/firstcomposeproject/ui/theme/Type.kt | 1773420976 |
package com.example.firstcomposeproject.di
import android.content.Context
import com.example.firstcomposeproject.presentation.main.MainActivity
import dagger.BindsInstance
import dagger.Component
@ApplicationScope
@Component(
modules = [
DataModule::class,
ViewModelModule::class
]
)
interface ApplicationComponent {
fun inject(mainActivity: MainActivity)
fun getCommentsScreenComponentFactory(): CommentScreenComponent.Factory
@Component.Factory
interface Factory {
fun create(
@BindsInstance context: Context
): ApplicationComponent
}
} | P0012_FirstComposeProject/app/src/main/java/com/example/firstcomposeproject/di/ApplicationComponent.kt | 3342700958 |
package com.example.firstcomposeproject.di
import android.content.Context
import com.example.firstcomposeproject.data.network.ApiFactory
import com.example.firstcomposeproject.data.network.ApiService
import com.example.firstcomposeproject.data.repositories.NewsFeedRepositoryImpl
import com.example.firstcomposeproject.domain.Repository
import com.vk.api.sdk.VKPreferencesKeyValueStorage
import dagger.Binds
import dagger.Module
import dagger.Provides
@Module
interface DataModule {
@ApplicationScope
@Binds
fun bindRepository(impl: NewsFeedRepositoryImpl): Repository
companion object {
@ApplicationScope
@Provides
fun provideApiService(): ApiService {
return ApiFactory.apiService
}
@ApplicationScope
@Provides
fun provideVkStorage(
context: Context
): VKPreferencesKeyValueStorage {
return VKPreferencesKeyValueStorage(context)
}
}
}
| P0012_FirstComposeProject/app/src/main/java/com/example/firstcomposeproject/di/DataModule.kt | 2340298835 |
package com.example.firstcomposeproject.di
import com.example.firstcomposeproject.domain.entities.FeedPost
import com.example.firstcomposeproject.presentation.ViewModelFactory
import dagger.BindsInstance
import dagger.Subcomponent
@Subcomponent(
modules = [
CommentViewModelModule::class
]
)
interface CommentScreenComponent {
fun getViewModelFactory(): ViewModelFactory
@Subcomponent.Factory
interface Factory {
fun create(
@BindsInstance feedPost: FeedPost
): CommentScreenComponent
}
} | P0012_FirstComposeProject/app/src/main/java/com/example/firstcomposeproject/di/CommentScreenComponent.kt | 1326554663 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.