content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.myscreensaver.network import com.example.myscreensaver.network.data.Images import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface PixabayApiService { @GET("/api") suspend fun getImages( @Query("key") key: String = "39075471-061c40a0b606c525ec8686d8d" ) : Response<Images> }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/PixabayApiService.kt
2279068908
package com.example.myscreensaver.network.pexel_model import com.google.gson.annotations.SerializedName data class SingleImageSrcPexel( @SerializedName("original" ) var original : String? = null, @SerializedName("large2x" ) var large2x : String? = null, @SerializedName("large" ) var large : String? = null, @SerializedName("medium" ) var medium : String? = null, @SerializedName("small" ) var small : String? = null, @SerializedName("portrait" ) var portrait : String? = null, @SerializedName("landscape" ) var landscape : String? = null, @SerializedName("tiny" ) var tiny : String? = null )
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/pexel_model/SingleImageSrcPexel.kt
2217473316
package com.example.myscreensaver.network.pexel_model import com.google.gson.annotations.SerializedName data class ImagesPexel( @SerializedName("page" ) var page : Int? = null, @SerializedName("per_page" ) var perPage : Int? = null, @SerializedName("photos" ) var photos : ArrayList<SingleImagePexel> = arrayListOf(), @SerializedName("next_page" ) var nextPage : String? = null )
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/pexel_model/ImagesPexel.kt
1736448420
package com.example.myscreensaver.network.pexel_model import com.google.gson.annotations.SerializedName data class SingleImagePexel( @SerializedName("id" ) var id : Int? = null, @SerializedName("width" ) var width : Int? = null, @SerializedName("height" ) var height : Int? = null, @SerializedName("url" ) var url : String? = null, @SerializedName("photographer" ) var photographer : String? = null, @SerializedName("photographer_url" ) var photographerUrl : String? = null, @SerializedName("photographer_id" ) var photographerId : Int? = null, @SerializedName("avg_color" ) var avgColor : String? = null, @SerializedName("src" ) var src : SingleImageSrcPexel? = SingleImageSrcPexel(), @SerializedName("liked" ) var liked : Boolean? = null, @SerializedName("alt" ) var alt : String? = null )
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/pexel_model/SingleImagePexel.kt
1488746048
package com.example.myscreensaver.network import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitClientPixabay { // https://pixabay.com/api/?key=39075471-061c40a0b606c525ec8686d8d private const val BASE_URL = "https://pixabay.com/" fun getInstance() : Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } val INSTANCE= getInstance().create(PixabayApiService::class.java) }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/RetrofitClientPixabay.kt
1868283148
package com.example.myscreensaver.network import com.example.myscreensaver.network.pexel_model.ImagesPexel import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Query interface PexelApiService { @GET("curated") suspend fun getCuratedImages( @Header("Authorization") authorization: String= "ZUZ1tmEskXZyRk7QqPvVcPKpJyQkPwnzt2aA5377lTLrhlGiRxcWnjfr" , @Query("page") page: Int? = 1, @Query("per_page") per_page: Int? = 80 ) : Response<ImagesPexel> @GET("search") suspend fun getSearchedImages( @Query("query") query: String, @Header("Authorization") authorization: String= "ZUZ1tmEskXZyRk7QqPvVcPKpJyQkPwnzt2aA5377lTLrhlGiRxcWnjfr", @Query("page") page: Int? = 1, @Query("per_page") per_page: Int? = 80 ) : Response<ImagesPexel> }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/PexelApiService.kt
1661124305
package com.example.myscreensaver.network import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitClientPexel { private const val BASE_URL = "https://api.pexels.com/v1/" fun getInstance() : Retrofit { return Retrofit.Builder() .baseUrl(RetrofitClientPexel.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } val INSTANCE= getInstance().create(PexelApiService::class.java) }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/RetrofitClientPexel.kt
3022607151
package com.example.myscreensaver.network.data import com.google.gson.annotations.SerializedName data class Images( @SerializedName("total" ) var total : Long? = null, @SerializedName("totalHits" ) var totalHits : Long? = null, @SerializedName("hits" ) var hits : List<SingleImage> )
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/data/Images.kt
4138613785
package com.example.myscreensaver.network.data import com.google.gson.annotations.SerializedName data class SingleImage( @SerializedName("id" ) var id : Long? = null, @SerializedName("pageURL" ) var pageURL : String? = null, @SerializedName("type" ) var type : String? = null, @SerializedName("tags" ) var tags : String? = null, @SerializedName("previewURL" ) var previewURL : String? = null, @SerializedName("previewWidth" ) var previewWidth : Long? = null, @SerializedName("previewHeight" ) var previewHeight : Long? = null, @SerializedName("webformatURL" ) var webformatURL : String? = null, @SerializedName("webformatWidth" ) var webformatWidth : Long? = null, @SerializedName("webformatHeight" ) var webformatHeight : Long? = null, @SerializedName("largeImageURL" ) var largeImageURL : String? = null, @SerializedName("imageWidth" ) var imageWidth : Long? = null, @SerializedName("imageHeight" ) var imageHeight : Long? = null, @SerializedName("imageSize" ) var imageSize : Long? = null, @SerializedName("views" ) var views : Long? = null, @SerializedName("downloads" ) var downloads : Long? = null, @SerializedName("collections" ) var collections : Long? = null, @SerializedName("likes" ) var likes : Long? = null, @SerializedName("comments" ) var comments : Long? = null, @SerializedName("user_id" ) var userId : Long? = null, @SerializedName("user" ) var user : String? = null, @SerializedName("userImageURL" ) var userImageURL : String? = null )
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/network/data/SingleImage.kt
1422338698
package com.example.myscreensaver import android.app.WallpaperManager import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.util.DisplayMetrics import android.util.Log import android.view.WindowManager import androidx.core.content.getSystemService import com.example.myscreensaver.service.MyService import com.squareup.picasso.Picasso import com.squareup.picasso.Target import kotlin.random.Random class MyScreenSaverUtils { val TAG = "raj_dynamic_wallpaper" fun setWallpaper(context: Context) { /*Glide.with(context).asBitmap().load("https://picsum.photos/200").into(object : Target<Bitmap> { override fun onStart() { TODO("Not yet implemented") } override fun onStop() { TODO("Not yet implemented") } override fun onDestroy() { TODO("Not yet implemented") } override fun onLoadStarted(placeholder: Drawable?) { TODO("Not yet implemented") } override fun onLoadFailed(errorDrawable: Drawable?) { TODO("Not yet implemented") } override fun onLoadCleared(placeholder: Drawable?) { TODO("Not yet implemented") } override fun getSize(cb: SizeReadyCallback?) { TODO("Not yet implemented") } override fun removeCallback(cb: SizeReadyCallback?) { TODO("Not yet implemented") } override fun setRequest(request: Request?) { TODO("Not yet implemented") } override fun getRequest(): Request? { TODO("Not yet implemented") } override fun onResourceReady(resource: Bitmap?, transition: Transition<in Bitmap>?) { val wallpaperManager= WallpaperManager.getInstance(context) wallpaperManager.setBitmap(resource) } })*/ /*var imageList= ArrayList<String>() imageList.add("https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg") imageList.add("https://picsum.photos/201") imageList.add("https://picsum.photos/202") val random = Random.nextInt(0, 2) val prev=random val imgUrl= imageList.get(random) Log.d(TAG, "setWallpaper: imgurl_selected=" + imgUrl)*/ //context.getSystemService<MyService>().wallpaperDesiredMinimumHeight Picasso.with(context).load("https://cdn.pixabay.com/user/2023/08/31/14-34-06-589_250x250.jpg").into(object : Target { override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) { // Log.d(TAG, "setWallpaper: imgurl_loaded=" + imgUrl) val displayMetrics = DisplayMetrics() //getWindowManager().getDefaultDisplay().getMetrics(displayMetrics) val height = context.wallpaperDesiredMinimumHeight val width = context.wallpaperDesiredMinimumWidth val bitmap2= bitmap?.let { Bitmap.createScaledBitmap(it, width, height, true) } val wallpaperManager= WallpaperManager.getInstance(context) wallpaperManager.setWallpaperOffsetSteps(1F, 1F); wallpaperManager.suggestDesiredDimensions(width, height); wallpaperManager.setBitmap(bitmap2) } override fun onBitmapFailed(errorDrawable: Drawable?) { //TODO("Not yet implemented") } override fun onPrepareLoad(placeHolderDrawable: Drawable?) { //TODO("Not yet implemented") } }) } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/MyScreenSaverUtils.kt
1834091012
package com.example.myscreensaver.adapters import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import com.example.myscreensaver.R import com.example.myscreensaver.network.data.Images import com.example.myscreensaver.network.pexel_model.ImagesPexel import com.example.myscreensaver.network.pexel_model.SingleImagePexel import com.squareup.picasso.Picasso class MyAdapter(private val images: List<SingleImagePexel>, private val context: Context) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view= LayoutInflater.from(parent.context).inflate(R.layout.single_image_item, parent, false) return MyViewHolder(view) } override fun getItemCount(): Int { return images.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { //Picasso.with(context).load(images.get(position).src?.portrait).into(holder.imageView) Glide.with(context).asBitmap().load(images.get(position).src?.portrait).diskCacheStrategy( DiskCacheStrategy.ALL).into(object : CustomTarget<Bitmap>() { override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { holder.imageView.setImageBitmap(resource) } override fun onLoadCleared(placeholder: Drawable?) { holder.imageView.setImageDrawable(placeholder) } }) } class MyViewHolder(val view: View) : RecyclerView.ViewHolder(view) { val imageView= view.findViewById<ImageView>(R.id.single_image) } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/adapters/MyAdapter.kt
1425327042
package com.example.myscreensaver import android.app.Activity import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.myscreensaver.adapters.MyAdapter import com.example.myscreensaver.network.pexel_model.ImagesPexel /** * A simple [Fragment] subclass. * Use the [MainViewFragment.newInstance] factory method to * create an instance of this fragment. */ class MainViewFragment(activity: Activity, var position: Int) : Fragment() { lateinit var mainActivity: MainActivity var images_recyclerview: RecyclerView?= null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainActivity= activity as MainActivity } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_main_view, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) images_recyclerview= view.findViewById(R.id.my_recyclerview) //fetch pexel images mainActivity.mainViewModel.imagesLiveData.observe(mainActivity, Observer { updateAdapter(it) }) if (position==0) { if (mainActivity.mainViewModel.categoryImageListMap.contains("All")) { var images= mainActivity.mainViewModel.categoryImageListMap.getValue("All") updateAdapter(images) } else { mainActivity.mainViewModel.getPexelImages() } } else { var query= Utils.getCategories().get(position) if (mainActivity.mainViewModel.categoryImageListMap.containsKey(query)) { var images= mainActivity.mainViewModel.categoryImageListMap.getValue(query) updateAdapter(images) } else { mainActivity.mainViewModel.getPexelImageForSearch(query) } } } fun updateAdapter(images: ImagesPexel) { images_recyclerview?.layoutManager= GridLayoutManager(mainActivity, 2) //images_recyclerview?.layoutManager. images_recyclerview?.adapter= MyAdapter(images.photos, mainActivity.applicationContext) images_recyclerview?.adapter!!.notifyDataSetChanged() } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/MainViewFragment.kt
3744571368
package com.example.myscreensaver import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class MainViewModelFactory(val mainRepository: MainRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return MainViewModel(mainRepository) as T } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/MainViewModelFactory.kt
1734980669
package com.example.myscreensaver.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import com.example.myscreensaver.Worker.MyWorker class MyReceiver : BroadcastReceiver() { val TAG = "raj_dynamic_wallpaper" override fun onReceive(context: Context?, intent: Intent?) { Log.d(TAG, "onReceive: invoked myreceiver") // We are starting MyService via a worker and not directly because since Android 7 // (but officially since Lollipop!), any process called by a BroadcastReceiver // (only manifest-declared receiver) is run at low priority and hence eventually // killed by Android. Docs: https://developer.android.com/guide/components/broadcasts#effects-process-state val workManager = WorkManager.getInstance(context!!) val oneTimeWorkRequest= OneTimeWorkRequest.Builder(MyWorker::class.java).build() workManager.enqueue(oneTimeWorkRequest) } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/receiver/MyReceiver.kt
2138444993
package com.example.myscreensaver.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import com.example.myscreensaver.MyScreenSaverUtils class ScreenLockReceiver : BroadcastReceiver() { val TAG = "raj_dynamic_wallpaper" override fun onReceive(context: Context?, intent: Intent?) { val action = intent?.action if(action== Intent.ACTION_SCREEN_ON) { Log.d(TAG, "onReceive: ACTION_SCREEN_ON") } else if (action== Intent.ACTION_SCREEN_OFF) { Log.d(TAG, "onReceive: ACTION_SCREEN_OFF") } else if(action==Intent.ACTION_USER_PRESENT) { Log.d(TAG, "onReceive: ACTION_USER_PRESENT") if (context != null) { MyScreenSaverUtils().setWallpaper(context) } } } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/receiver/ScreenLockReceiver.kt
1276673501
package com.example.myscreensaver.service import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Intent import android.content.IntentFilter import android.graphics.Color import android.os.Build import android.os.IBinder import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import com.example.myscreensaver.MainActivity import com.example.myscreensaver.R import com.example.myscreensaver.receiver.MyReceiver import com.example.myscreensaver.receiver.ScreenLockReceiver class MyService : Service() { val TAG = "raj_dynamic_wallpaper" val CHANNEL_ID= "notification_channel" private val screenLockReceiver: ScreenLockReceiver var isServiceRunning : Boolean= false companion object { var isServiceRunning = false } init { screenLockReceiver= ScreenLockReceiver() } @RequiresApi(Build.VERSION_CODES.O) override fun onCreate() { super.onCreate() Log.d(TAG, "onCreate: MyService invoked") createNotificationChannel() isServiceRunning= true // register receiver to listen for screen on events val intentFilter= IntentFilter() intentFilter.addAction(Intent.ACTION_SCREEN_ON) intentFilter.addAction(Intent.ACTION_SCREEN_OFF) intentFilter.addAction(Intent.ACTION_USER_PRESENT) registerReceiver(screenLockReceiver, intentFilter) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { //return super.onStartCommand(intent, flags, startId) val intent= Intent(this, MainActivity::class.java) val pendingIntent= PendingIntent.getService(this, 1000, intent, PendingIntent.FLAG_IMMUTABLE) val notification= NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Service is Running") .setContentText("Listening for on/off screen events") .setContentIntent(pendingIntent) .setSmallIcon(androidx.core.R.drawable.notification_bg) .setColor(Color.GREEN) .build() /* * A started service can use the startForeground API to put the service in a foreground state, * where the system considers it to be something the user is actively aware of and thus not * a candidate for killing when low on memory. */ startForeground(1, notification) return START_STICKY } override fun onBind(intent: Intent?): IBinder? { return null } override fun onDestroy() { Log.d(TAG, "onDestroy: MyService invoked") isServiceRunning= false stopForeground(true) //unregister receiver unregisterReceiver(screenLockReceiver) // call MyReceiver which will restart this service via a worker val broadcastIntent= Intent(this, MyReceiver::class.java) sendBroadcast(broadcastIntent) super.onDestroy() } @RequiresApi(Build.VERSION_CODES.O) fun createNotificationChannel() { val notificationChannel = NotificationChannel(CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT) val notificationManager= getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(notificationChannel) } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/service/MyService.kt
1928486173
package com.example.myscreensaver.Worker import android.content.Context import android.content.Intent import android.util.Log import androidx.core.content.ContextCompat import androidx.work.Worker import androidx.work.WorkerParameters import com.example.myscreensaver.service.MyService class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { val TAG = "raj_dynamic_wallpaper" override fun doWork(): Result { if(MyService.isServiceRunning==false){ Log.d(TAG, "starting service from doWork") val intent = Intent(this.applicationContext, MyService::class.java) /* * startForegroundService is similar to startService but with an implicit promise * that the service will call startForeground once it begins running. * The service is given an amount of time comparable to the ANR interval to do this, * otherwise the system will automatically stop the service and declare the app ANR. */ /* * startForegroundService is similar to startService but with an implicit promise * that the service will call startForeground once it begins running. * The service is given an amount of time comparable to the ANR interval to do this, * otherwise the system will automatically stop the service and declare the app ANR. */ ContextCompat.startForegroundService(this.applicationContext, intent) } return Result.success() } override fun onStopped() { Log.d(TAG, "onStopped called for: " + this.id) super.onStopped() } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/Worker/MyWorker.kt
4244709290
package com.example.myscreensaver import android.app.Activity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter class MainFragmentAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle, var activity: Activity): FragmentStateAdapter(fragmentManager, lifecycle) { override fun getItemCount(): Int { return Utils.getCategories().size } override fun createFragment(position: Int): Fragment { return MainViewFragment(activity, position) } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/MainFragmentAdapter.kt
2254627447
package com.example.myscreensaver import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class ActivityB : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_b) } }
Dynamic_Wallpaper/app/src/main/java/com/example/myscreensaver/ActivityB.kt
2649458923
package nbcdocker.learning.cicd import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.http.ResponseEntity import org.assertj.core.api.Assertions.assertThat @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class CicdApplicationTests { @Autowired lateinit var template: TestRestTemplate @Test fun contextLoads() { } @Test @DisplayName("/healthz 테스트") fun testHomeContollerHealthz() { val response: ResponseEntity<String> = template.getForEntity("/healthz", String::class.java) // 실패하는 경우 // assertThat(response.body).isEqualTo("on failed") // 성공하는 경우 assertThat(response.body).isEqualTo("healthz") } }
cicd-sample/src/test/kotlin/nbcdocker/learning/cicd/CicdApplicationTests.kt
2855086696
package nbcdocker.learning.cicd.controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class HomeController { @GetMapping("/") fun home(): String { return "home" } @GetMapping("/healthz") fun healthz(): String { return "healthz" } @GetMapping("/healthcheck") fun healthcheck(): String { return "healthcheck" } }
cicd-sample/src/main/kotlin/nbcdocker/learning/cicd/controller/HomeController.kt
637398822
package nbcdocker.learning.cicd import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class CicdApplication fun main(args: Array<String>) { runApplication<CicdApplication>(*args) }
cicd-sample/src/main/kotlin/nbcdocker/learning/cicd/CicdApplication.kt
1040481967
package com.example.testeve 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.testeve", appContext.packageName) } }
demo_audio_visualize/app/src/androidTest/java/com/example/testeve/ExampleInstrumentedTest.kt
569407228
package com.example.testeve 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) } }
demo_audio_visualize/app/src/test/java/com/example/testeve/ExampleUnitTest.kt
3199541758
package com.example.testeve import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { /* ********************************************************************** * Variable ********************************************************************** */ var isCheck = MutableLiveData<Boolean?>() }
demo_audio_visualize/app/src/main/java/com/example/testeve/MainViewModel.kt
1227497127
package com.example.testeve import android.os.Bundle import android.view.View import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import java.util.Random class MainActivity : AppCompatActivity() { // private var swipeRefreshLayout: SwipeRefreshLayout? = null // private var recyclerView: RecyclerView? = null // private var close: ImageView? = null // private var adapter: Adapter? = null // // private var data: ArrayList<Item> = ArrayList(mutableListOf( // Item("Facebook", "Meta", R.drawable.ic_link, false), // Item("Twitter", "Elon Musk", R.drawable.ic_linear, false), // Item("Instagram", "Facebook", R.drawable.ic_news, false), // Item("LinkedIn", "LinkedIn", R.drawable.ic_more, false), // Item("Youtube", "Youtube", R.drawable.ic_next, false), // Item("Whatsapp", "Whatsapp", R.drawable.ic_pass, false), // )) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(R.layout.activity_main) // // // Getting reference of swipeRefreshLayout and recyclerView //// swipeRefreshLayout = findViewById<View>(R.id.swipeRefreshLayout) as SwipeRefreshLayout // recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView // close = findViewById<View>(R.id.close) as ImageView // // // Setting the layout as Linear for vertical orientation to have swipe behavior // val linearLayoutManager = LinearLayoutManager(applicationContext) // recyclerView!!.layoutManager = linearLayoutManager // // // Sending reference and data to Adapter // adapter = Adapter(this@MainActivity, data) // // // Setting Adapter to RecyclerView // recyclerView!!.adapter = adapter // // // SetOnRefreshListener on SwipeRefreshLayout //// swipeRefreshLayout!!.setOnRefreshListener { //// swipeRefreshLayout!!.isRefreshing = false //// rearrangeItems() //// } // // close!!.setOnClickListener { // adapter!!.updateCheck(false) // adapter!!.clearCheck() // } } // private fun rearrangeItems() { // // Shuffling the data of ArrayList using system time // data.shuffle(Random(System.currentTimeMillis())) // adapter = Adapter(this@MainActivity, data) // recyclerView!!.adapter = adapter // } }
demo_audio_visualize/app/src/main/java/com/example/testeve/MainActivity.kt
2885839532
package com.example.testeve data class Item(val title: String, val subTitle: String, val icon: Int, var isChecked: Boolean)
demo_audio_visualize/app/src/main/java/com/example/testeve/Item.kt
3818388451
package com.example.testeve import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.compose.material3.ModalBottomSheet import com.example.testeve.databinding.ActivityRecordBinding import com.example.testeve.recorder.Recorder import com.example.testeve.utils.checkAudioPermission import com.example.testeve.utils.formatAsTime import com.example.testeve.utils.getDrawableCompat import kotlin.math.sqrt class RecordActivity : AppCompatActivity() { private lateinit var binding: ActivityRecordBinding private lateinit var recorder: Recorder companion object { private const val AUDIO_PERMISSION_REQUEST_CODE = 1 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRecordBinding.inflate(layoutInflater) setContentView(binding.root) initUI() // requestPermissions( // arrayOf( // Manifest.permission.READ_EXTERNAL_STORAGE, // Manifest.permission.WRITE_EXTERNAL_STORAGE, // Manifest.permission.RECORD_AUDIO, // ), // 123 // ) // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { // if (ContextCompat.checkSelfPermission( // this, // Manifest.permission.READ_EXTERNAL_STORAGE // ) != PackageManager.PERMISSION_GRANTED // ) { // ActivityCompat.requestPermissions( // this, // arrayOf<String>(Manifest.permission.READ_EXTERNAL_STORAGE), // 124 // ) // } // if (ContextCompat.checkSelfPermission( // this, // Manifest.permission.WRITE_EXTERNAL_STORAGE // ) != PackageManager.PERMISSION_GRANTED // ) { // ActivityCompat.requestPermissions( // this, // arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE), // 125 // ) // } // } else { // if (!Environment.isExternalStorageManager()) { // try { // val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) // intent.addCategory("android.intent.category.DEFAULT") // intent.setData( // Uri.parse( // String.format1( // "package:%s", // packageName // ) // ) // ) // startActivityForResult(intent, FACE_REGISTER_REQ_PERMISSION_CODE) // } catch (e: Exception) { // val intent = Intent() // intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) // startActivityForResult(intent, FACE_REGISTER_REQ_PERMISSION_CODE) // } // } else { // val intent = Intent() // } // } } private fun initUI() = with(binding) { startRecord.setOnClickListener { if(checkAudioPermission(AUDIO_PERMISSION_REQUEST_CODE)){ recorder.toggleRecording() } } recordingView.visualizer.ampNormalizer = { sqrt(it.toFloat()).toInt() } recordingView.playVisualizer.visibility = View.GONE recordingView.replayControl.visibility = View.GONE } private fun listenOnRecorderStates() = with(binding) { recorder = Recorder.getInstance(applicationContext).init().apply { onStart = { recordingView.root.visibility = View.VISIBLE startRecord.icon = getDrawableCompat(R.drawable.ic_close) } onStop = { recordingView.visualizer.clear() recordingView.root.visibility = View.GONE recordingView.timelineTextView.text = 0L.formatAsTime() startRecord.icon = getDrawableCompat(R.drawable.ic_record) val modalBottomSheet = RecordDialogFragment() modalBottomSheet.show(supportFragmentManager, RecordDialogFragment.TAG) // startActivity(Intent(this@MainActivity, PlayActivity::class.java)) } onAmpListener = { runOnUiThread { if (recorder.isRecording) { recordingView.timelineTextView.text = recorder.getCurrentTime().formatAsTime() recordingView.visualizer.addAmp(it, tickDuration) } } } } } override fun onStart() { super.onStart() listenOnRecorderStates() } override fun onStop() { recorder.release() super.onStop() } }
demo_audio_visualize/app/src/main/java/com/example/testeve/RecordActivity.kt
124330529
package com.example.testeve.utils open class SingletonHolder<out T : Any, in A>(creator: (A) -> T) { private var creator: ((A) -> T)? = creator @Volatile private var instance: T? = null fun getInstance(arg: A): T { val checkInstance = instance if (checkInstance != null) { return checkInstance } return synchronized(this) { val checkInstanceAgain = instance if (checkInstanceAgain != null) { checkInstanceAgain } else { val created = creator!!(arg) instance = created creator = null created } } } }
demo_audio_visualize/app/src/main/java/com/example/testeve/utils/SingletonHolder.kt
245601214
package com.example.testeve.utils import android.content.Context import android.widget.Toast import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat fun Context.showToast(string: String) { Toast.makeText(this, string, Toast.LENGTH_LONG).apply { show() } } fun Context.getDrawableCompat(@DrawableRes resId: Int) = ContextCompat.getDrawable(this, resId)
demo_audio_visualize/app/src/main/java/com/example/testeve/utils/ContextUtils.kt
1828775897
package com.example.testeve.utils import android.annotation.SuppressLint import java.util.concurrent.TimeUnit @SuppressLint("DefaultLocale") fun Long.formatAsTime(): String { if(this >= 0){ val seconds = (TimeUnit.MILLISECONDS.toSeconds(this) % 60).toInt() val minutes = (TimeUnit.MILLISECONDS.toMinutes(this) % 60).toInt() return when (val hours = (TimeUnit.MILLISECONDS.toHours(this)).toInt()) { 0 -> "$minutes:$seconds" // Format MM:SS else -> "$hours:$minutes:$seconds" // Format HH:MM:SS } } else { return "00:00" } } // parse HH:MM:SS to long @SuppressLint("DefaultLocale") fun String.parseTimeToMillis(): Long? { val parts = this.split(":") return when (parts.size) { 2 -> { // Format MM:SS val minutes = parts[0].toIntOrNull() ?: return null val seconds = parts[1].toIntOrNull() ?: return null if (minutes !in 0..59 || seconds !in 0..59) return null TimeUnit.MINUTES.toMillis(minutes.toLong()) + TimeUnit.SECONDS.toMillis(seconds.toLong()) } 3 -> { // Format HH:MM:SS val hours = parts[0].toIntOrNull() ?: return null val minutes = parts[1].toIntOrNull() ?: return null val seconds = parts[2].toIntOrNull() ?: return null if (hours < 0 || minutes !in 0..59 || seconds !in 0..59) return null TimeUnit.HOURS.toMillis(hours.toLong()) + TimeUnit.MINUTES.toMillis(minutes.toLong()) + TimeUnit.SECONDS.toMillis(seconds.toLong()) } else -> null } }
demo_audio_visualize/app/src/main/java/com/example/testeve/utils/NumberUtils.kt
2780336699
package com.example.testeve.utils import android.Manifest import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.os.Build fun Activity.checkAudioPermission(requestCode: Int): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!isGranted(Manifest.permission.RECORD_AUDIO)) { requestPermissions( arrayOf(Manifest.permission.RECORD_AUDIO), requestCode ) return false } } return true } fun Context.isGranted(permissionCode: String) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkSelfPermission(permissionCode) == PackageManager.PERMISSION_GRANTED } else { true }
demo_audio_visualize/app/src/main/java/com/example/testeve/utils/PermissionUtils.kt
2719748405
package com.example.testeve.utils import android.content.Context import androidx.core.net.toUri import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.MediaSource import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.upstream.DataSource import com.google.android.exoplayer2.upstream.DataSpec import com.google.android.exoplayer2.upstream.FileDataSource import java.io.File const val WAVE_HEADER_SIZE = 44 val Context.recordFile: File get() = File(filesDir, "rec.wav") fun File.toMediaSource(): MediaSource = DataSpec(this.toUri()) .let { FileDataSource().apply { open(it) } } .let { DataSource.Factory { it } } .let { ProgressiveMediaSource.Factory(it, DefaultExtractorsFactory()) } .createMediaSource(MediaItem.fromUri(this.toUri()))
demo_audio_visualize/app/src/main/java/com/example/testeve/utils/FileUtils.kt
239913296
package com.example.testeve import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.res.ResourcesCompat import androidx.lifecycle.lifecycleScope import com.example.testeve.databinding.FragmentRecordDialogBinding import com.example.testeve.player.AudioPlayer import com.example.testeve.utils.formatAsTime import com.example.testeve.utils.parseTimeToMillis import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlin.math.sqrt class RecordDialogFragment : BottomSheetDialogFragment() { private var _binding: FragmentRecordDialogBinding? = null private val binding get() = _binding!! private lateinit var player: AudioPlayer private var currentTime: Long = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRecordDialogBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { } companion object { const val TAG = "ModalBottomSheet" const val SEEK_OVER_AMOUNT = 5000 fun newInstance(itemCount: Int): RecordDialogFragment = RecordDialogFragment().apply { arguments = Bundle().apply { } } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onStart() { super.onStart() listenOnPlayerStates() initUI() } override fun onStop() { player.release() super.onStop() } @SuppressLint("SetTextI18n") private fun initUI() = with(binding) { replayView.playVisualizer.apply { ampNormalizer = { sqrt(it.toFloat()).toInt() } onStartSeeking = { player.pause() } onSeeking = { replayView.timelineTextView.text = it.formatAsTime() } onFinishedSeeking = { time, isPlayingBefore -> player.seekTo(time) if (isPlayingBefore) { player.resume() } } onAnimateToPositionFinished = { time, isPlaying -> updateTime(time, isPlaying) player.seekTo(time) } } replayView.replayControl.setOnClickListener { player.togglePlay() } currentTime = replayView.timelineTextView.text.toString().parseTimeToMillis()!! for5.setOnClickListener { replayView.playVisualizer.seekOver(SEEK_OVER_AMOUNT) } back5.setOnClickListener { replayView.playVisualizer.seekOver(-SEEK_OVER_AMOUNT) } lifecycleScope.launchWhenCreated { val amps = player.loadAmps() replayView.playVisualizer.setWaveForm(amps, player.tickDuration) } } private fun listenOnPlayerStates() = with(binding) { player = AudioPlayer.getInstance(requireContext()).init().apply { onStart = { replayView.replayControl.icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_pause_24, requireActivity().theme) } onStop = { replayView.replayControl.icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_play_arrow_24, requireActivity().theme) } onPause = { replayView.replayControl.icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_play_arrow_24, requireActivity().theme) } onResume = { replayView.replayControl.icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_pause_24, requireActivity().theme) } onProgress = { time, isPlaying -> updateTime(time, isPlaying) } } } private fun updateTime(time: Long, isPlaying: Boolean) = with(binding) { replayView.timelineTextView.text = time.formatAsTime() replayView.playVisualizer.updateTime(time, isPlaying) } }
demo_audio_visualize/app/src/main/java/com/example/testeve/RecordDialogFragment.kt
3958026922
package com.example.testeve.recorder import android.content.Context import android.media.AudioFormat import android.media.AudioRecord import com.example.testeve.utils.SingletonHolder import com.example.testeve.utils.recordFile import com.github.squti.androidwaverecorder.WaveConfig import com.github.squti.androidwaverecorder.WaveRecorder class Recorder private constructor(context: Context) { var onStart: (() -> Unit)? = null var onStop: (() -> Unit)? = null var onAmpListener: ((Int) -> Unit)? = null set(value) { recorder.onAmplitudeListener = value field = value } private var startTime: Long = 0 private val recordingConfig = WaveConfig() private val appContext = context.applicationContext private lateinit var recorder: WaveRecorder var isRecording = false private set fun init(): Recorder { recorder = WaveRecorder(appContext.recordFile.toString()) .apply { waveConfig = recordingConfig } return this } fun toggleRecording() { isRecording = if (!isRecording) { startTime = System.currentTimeMillis() recorder.startRecording() onStart?.invoke() true } else { recorder.stopRecording() onStop?.invoke() false } } fun getCurrentTime() = System.currentTimeMillis() - startTime val bufferSize: Int get() = AudioRecord.getMinBufferSize( recordingConfig.sampleRate, recordingConfig.channels, recordingConfig.audioEncoding ) val tickDuration: Int get() = (bufferSize.toDouble() * 1000 / byteRate).toInt() private val channelCount: Int get() = if (recordingConfig.channels == AudioFormat.CHANNEL_IN_MONO) 1 else 2 private val byteRate: Long get() = (bitPerSample * recordingConfig.sampleRate * channelCount / 8).toLong() private val bitPerSample: Int get() = when (recordingConfig.audioEncoding) { AudioFormat.ENCODING_PCM_8BIT -> 8 AudioFormat.ENCODING_PCM_16BIT -> 16 else -> 16 } fun release() { onStart = null onStop = null recorder.onAmplitudeListener = null } companion object : SingletonHolder<Recorder, Context>(::Recorder) }
demo_audio_visualize/app/src/main/java/com/example/testeve/recorder/Recorder.kt
3027270066
package com.example.testeve import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.ImageButton import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar open class Adapter (var context: Context, private var data: ArrayList<Item>) : RecyclerView.Adapter<Adapter.ViewHolder>() { private var isChecked: Boolean = false private var itemSelectedList = mutableListOf<Int>() // private val viewBinderHelper = ViewBinderHelper() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_list, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { // viewBinderHelper.setOpenOnlyOne(true) // val item = data[position] // holder.images.setImageResource(item.icon) // holder.title.text = item.title // holder.subTitle.text = item.subTitle // holder.checkBox.isChecked = item.isChecked // holder.checkBox.visibility = if (this.isChecked) View.VISIBLE else View.GONE // holder.delete.setOnClickListener { // Snackbar.make(holder.itemView, "${item.title} deleted", Snackbar.LENGTH_SHORT).show() // } // // holder.checkBox.setOnClickListener { // selectItem(position, item) // } // // holder.mainLayout.setOnClickListener { // if (isChecked) { // selectItem(position, item) // } else { // Snackbar.make(holder.itemView, item.title, Snackbar.LENGTH_SHORT).show() // } // } // // holder.mainLayout.setOnLongClickListener { // selectItem(position, item) // false // } // viewBinderHelper.bind(holder.swipeRevealLayout, item.subTitle) } override fun getItemCount(): Int { return data.size } inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { // var images: ImageView // var title: TextView // var subTitle: TextView // var checkBox: CheckBox // var delete: ImageButton // var swipeRevealLayout: SwipeRevealLayout // var mainLayout: LinearLayout // init { // images = view.findViewById<View>(R.id.imageIcon) as ImageView // title = view.findViewById<View>(R.id.headline) as TextView // subTitle = view.findViewById<View>(R.id.subHeadline) as TextView // checkBox = view.findViewById<View>(R.id.checkBox) as CheckBox // delete = view.findViewById<View>(R.id.delete) as ImageButton //// swipeRevealLayout = view.findViewById<View>(R.id.swipeRevealLayout) as SwipeRevealLayout // mainLayout = view.findViewById<View>(R.id.mainLayout) as LinearLayout // } } fun updateCheck(isChecked: Boolean) { this.isChecked = isChecked notifyDataSetChanged() } fun clearCheck() { itemSelectedList.clear() for (item: Item in data) { item.isChecked = false } Log.d("itemSelectedList", "items : ${itemSelectedList.toMutableList().sort()}") notifyDataSetChanged() } private fun selectItem(position: Int, item: Item) { isChecked = true if (itemSelectedList.contains(position)){ itemSelectedList.remove(position) item.isChecked = false }else { itemSelectedList.add(position) item.isChecked = true } notifyDataSetChanged() } }
demo_audio_visualize/app/src/main/java/com/example/testeve/Adapter.kt
685369809
package com.example.testeve.player import android.content.Context import android.util.Log import com.example.testeve.recorder.Recorder import com.google.android.exoplayer2.ExoPlaybackException import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.SimpleExoPlayer import com.example.testeve.utils.SingletonHolder import com.example.testeve.utils.WAVE_HEADER_SIZE import com.example.testeve.utils.recordFile import com.example.testeve.utils.toMediaSource import com.google.android.exoplayer2.PlaybackException import com.google.firebase.firestore.EventListener import kotlinx.coroutines.* import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.flow.flow import java.io.File import java.nio.ByteBuffer import java.nio.ByteOrder class AudioPlayer private constructor(context: Context) : Player.Listener { private val appContext = context.applicationContext var onProgress: ((Long, Boolean) -> Unit)? = null var onStart: (() -> Unit)? = null var onStop: (() -> Unit)? = null var onPause: (() -> Unit)? = null var onResume: (() -> Unit)? = null val tickDuration = Recorder.getInstance(this.appContext).tickDuration private val coroutineScope = CoroutineScope(Dispatchers.Main) private var loopingFlowJob: Job? = null private var loopingFlow = flow { while (true) { emit(Unit) delay(LOOP_DURATION) } } private val recordFile = context.recordFile private val bufferSize = Recorder.getInstance(context).bufferSize private lateinit var player: ExoPlayer fun init(): AudioPlayer { if (::player.isInitialized) { player.release() } player = SimpleExoPlayer.Builder(appContext).build().apply { setMediaSource(recordFile.toMediaSource()) prepare() addListener(this@AudioPlayer) } return this } fun togglePlay() { if (!player.isPlaying) { resume() } else { pause() } } fun seekTo(time: Long) { player.seekTo(time) } fun resume() { player.play() updateProgress() onResume?.invoke() } fun pause() { player.pause() updateProgress() onPause?.invoke() } private fun updateProgress(position: Long = player.currentPosition) { onProgress?.invoke(position, player.playWhenReady) } @Suppress("BlockingMethodInNonBlockingContext") suspend fun loadAmps(): List<Int> = withContext(IO) { val amps = mutableListOf<Int>() val buffer = ByteArray(bufferSize) File(recordFile.toString()).inputStream().use { it.skip(WAVE_HEADER_SIZE.toLong()) var count = it.read(buffer) while (count > 0) { amps.add(buffer.calculateAmplitude()) count = it.read(buffer) } } amps } private fun ByteArray.calculateAmplitude(): Int { return ShortArray(size / 2).let { ByteBuffer.wrap(this) .order(ByteOrder.LITTLE_ENDIAN) .asShortBuffer() .get(it) it.maxOrNull()?.toInt() ?: 0 } } override fun onPlaybackStateChanged(playbackState: Int) { super.onPlaybackStateChanged(playbackState) when (playbackState) { Player.STATE_ENDED -> { updateProgress(player.duration) onStop?.invoke() reset() } Player.STATE_READY -> Unit Player.STATE_BUFFERING -> Unit Player.STATE_IDLE -> Unit } } private fun reset() { player.prepare() player.pause() player.seekTo(0) } override fun onIsPlayingChanged(isPlaying: Boolean) { super.onIsPlayingChanged(isPlaying) if (isPlaying) { loopingFlowJob?.cancel() loopingFlowJob = coroutineScope.launch { loopingFlow.collect { updateProgress() } } onStart?.invoke() } else { loopingFlowJob?.cancel() } } override fun onPlayerError(error: PlaybackException) { super.onPlayerError(error) Log.e(TAG, error.toString(), error) } fun release() { player.release() onProgress = null onStart = null onStop = null onPause = null onResume = null } companion object : SingletonHolder<AudioPlayer, Context>(::AudioPlayer) { private const val LOOP_DURATION = 20L private val TAG = AudioPlayer::class.simpleName } }
demo_audio_visualize/app/src/main/java/com/example/testeve/player/AudioPlayer.kt
866228201
fun main(args: Array<String>) { val matriz: Array<Array<Float>> = arrayOf( arrayOf(2.5f,-6.3f,14.7f,4.0f), arrayOf(10.8f,12.4f,-8.2f,5.5f), arrayOf(-7.2f,3.1f,17.7f,-9.1f) ) val newMatriz = arrayOf( floatArrayOf(0.0f,0.0f,0.0f,0.0f,0.0f), floatArrayOf(0.0f,0.0f,0.0f,0.0f,0.0f), floatArrayOf(0.0f,0.0f,0.0f,0.0f,0.0f), floatArrayOf(0.0f,0.0f,0.0f,0.0f,0.0f) ) imprimirPrimera(matriz) println() copia(matriz,newMatriz) fila(newMatriz) columna(newMatriz) imprimirSegunda(newMatriz) } fun imprimirSegunda(newMatriz: Array<FloatArray>) { for (i in newMatriz.indices){ for (j in 0 .. newMatriz.size){ print("[${newMatriz[i][j]}]") } println() } } fun imprimirPrimera(matriz: Array<Array<Float>>) { for (i in matriz.indices){ for (j in 0.. matriz.size){ print("[${matriz[i][j]}]") } println() } } fun copia(matriz: Array<Array<Float>>, newMatriz: Array<FloatArray>) { for (i in matriz.indices){ for (j in 0 .. matriz.size){ newMatriz[i][j] = matriz[i][j] } } } fun fila(newMatriz: Array<FloatArray>){ for (i in newMatriz.indices){ for (j in 0 ..newMatriz.size){ if (i < 3 && j < 4 ){ newMatriz[i][4] += newMatriz[i][j] } } } } fun columna(newMatriz: Array<FloatArray>) { for (i in newMatriz.indices){ for (j in 0 ..newMatriz.size){ var prueba = 0.0f if ( i < 3 && j < 4 ){ newMatriz[3][j] += newMatriz[i][j] } } } }
ejercicioMatriz/ejercicio02/matrizSuma/src/main/kotlin/Main.kt
3139131438
fun main(args: Array<String>) { val matriz = arrayOf(arrayOf(1,2,3), arrayOf(4,5,6), arrayOf(7,8,9)) val vector = IntArray(3) suma(matriz, vector) imprimirVector(vector, matriz) println(diagonalDerecha(matriz)) println(diagonalIzquierda(matriz)) } fun diagonalDerecha(matriz: Array<Array<Int>>): Int { var numero = 0 for ( i in matriz.indices){ numero+=matriz[i][i] } return numero } fun diagonalIzquierda(matriz: Array<Array<Int>>): Int { var resta = 0 for (i in (matriz.size -1 downTo 0)){ resta+=matriz[i][i] } return resta } fun imprimirVector(vector: IntArray, matriz: Array<Array<Int>>) { for (i in vector.indices){ print("[${vector[i]}]") } println() for (i in matriz.indices){ for (j in matriz.indices){ print("[${matriz[i][j]}]") } println() } } fun suma(matriz: Array<Array<Int>>, vector: IntArray) { for (i in matriz.indices){ for (j in matriz.indices){ if (matriz[i][j]== matriz[0][j]){ vector[0]+=matriz[i][j] } if (matriz[i][j]== matriz[1][j]){ vector[1]+=matriz[i][j] } if (matriz[i][j]== matriz[2][j]){ vector[2]+=matriz[i][j] } } } }
ejercicioMatriz/ejercicio03/SumaAlVector/src/main/kotlin/Main.kt
1982305742
const val MAX = 5 fun main() { val matrix = Array(MAX) { IntArray(MAX) } initMatrix(matrix) printMatrix(matrix) conDobleBuffer(matrix) println("FIN!") println() } // Ponemos 0 o 1 si la posición está vacía fun initMatrix(matrix: Array<IntArray>) { val maxUnos = 1 // sorteo de maxUnos posiciones mientras que no sea 0 repeat(maxUnos) { var esCero = false do { val fila = (0..<MAX).random() val columna = (0..<MAX).random() if (matrix[fila][columna] == 0) { matrix[fila][columna] = 1 esCero = true } } while (!esCero) } } fun printMatrix(matrix: Array<IntArray>) { println() for (i in matrix.indices) { for (j in matrix[i].indices) { print(matrix[i][j]) } println() } } fun conDobleBuffer(matrix: Array<IntArray>) { val timeMax = 10_000 var time = 0 var matrixLectura = clonarMatriz(matrix) do { // Intercambiamos las matrices val matrixEscritura = clonarMatriz(matrixLectura) // Acción moverLosUnosConDobleBuffer(matrixLectura, matrixEscritura) // Intercambiamos de nuevo matrixLectura = clonarMatriz(matrixEscritura) printMatrix(matrixLectura) Thread.sleep(1000) time += 1_000 } while (time < timeMax) } fun clonarMatriz(matrixLectura: Array<IntArray>): Array<IntArray> { val matrixEscritura = Array(MAX) { IntArray(MAX) } for (fila in matrixLectura.indices) { for (columna in matrixLectura[fila].indices) { matrixEscritura[fila][columna] = matrixLectura[fila][columna] } } return matrixEscritura } fun moverLosUnosConDobleBuffer(matrixLectura: Array<IntArray>, matrixEscritura: Array<IntArray>) { for (fila in matrixLectura.indices) { for (columna in matrixLectura[fila].indices) { if (matrixLectura[fila][columna] == 1) { // Mover aleatoriamente a una posicion que tenga un 0 var esCero = false do { val nuevaFila = (0 until MAX).random() val nuevaColumna = (0 until MAX).random() if (matrixEscritura[nuevaFila][nuevaColumna] == 0) { matrixEscritura[fila][columna] = 0 matrixEscritura[nuevaFila][nuevaColumna] = 1 esCero = true } } while (!esCero) } } } }
ejercicioMatriz/ejercicio03/doubleBuffer/src/main/kotlin/Main.kt
3752237833
fun main(args: Array<String>) { val matrizO = arrayOf(arrayOf(1,2,3), arrayOf(4,5,6), arrayOf(7,8,9)) val matrizP = Array(3) {IntArray(3)} var c1 = 0 var c2 = 0 var f1 = 0 var f2 = 0 println("que fila quieres intercambiar") f1 = readln().toIntOrNull()?:0 println("otra fila") f2 = readln().toIntOrNull()?:0 fila(matrizO, matrizP, f1, f2) println("que columna quieres intercambiar") c1 = readln().toIntOrNull()?:0 println("otra columna") c2 = readln().toIntOrNull()?:0 columna(matrizO, matrizP, c1, c2) nada(matrizP, matrizO) imprimirMatrizO(matrizO) println() imprimir(matrizP) } fun imprimirMatrizO(matrizO: Array<Array<Int>>) { for (i in matrizO.indices) { for (j in matrizO.indices) { print("[${matrizO[i][j]}]") } println() } } fun imprimir(matrizP: Array<IntArray>) { for (i in matrizP.indices) { for (j in matrizP.indices) { print("[${matrizP[i][j]}]") } println() } } fun nada(matrizP: Array<IntArray>, matrizO: Array<Array<Int>>) { for (i in matrizP.indices) { for (j in matrizP.indices) { if (matrizP[i][j] == 0) { matrizP[i][j] = matrizO[i][j] } } } } fun fila(matrizO: Array<Array<Int>>, matrizP: Array<IntArray>, f1: Int, f2: Int) { for (i in matrizO.indices) { for (j in matrizO.indices) { matrizP[f1][j] = matrizO[f2][j] matrizP[f2][j] = matrizO[f1][j] } } } fun columna(matrizO: Array<Array<Int>>, matrizP: Array<IntArray>, c1: Int, c2: Int) { for (i in matrizO.indices) { for (j in matrizO.indices) { matrizP[i][c1] = matrizO[i][c2] matrizP[i][c2] = matrizO[i][c1] } } }
ejercicioMatriz/ejercicio10/permetuar/src/main/kotlin/Main.kt
2829243584
fun main(args: Array<String>) { var columna = 0 var fila = 0 var r1 = 0 var r2 = 0 var matrizO = arrayOf( arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]") ) colocarMosca(matrizO) do { println("en que fila esta") fila= readln().toIntOrNull()?:0 println("en que columna esta") columna= readln().toIntOrNull()?:0 uff(matrizO,fila,columna) }while ( muerta(matrizO, columna,fila)) println("muerta") } fun colocarMosca(matrizO: Array<Array<String>>){ for (i in matrizO.indices){ for (j in matrizO.indices){ if (matrizO[i][j] == "[M]"){ matrizO[i][j] = "[ ]" } } } var i = (0..4).random() var j = (0..4).random() matrizO[i][j] = "[M]" } fun uff(matrizO: Array<Array<String>>, columna: Int, fila: Int) { if (muerta(matrizO, columna, fila)){} else if ((columna + 1 < matrizO.size) && (matrizO[fila][columna + 1] == "[M]" || (columna - 1 >= 0 && matrizO[fila][columna - 1] == "[M]"))) { imprimirMatriz(matrizO) colocarMosca(matrizO) println("casi pero no") }else if ((fila + 1 < matrizO.size) && (matrizO[fila + 1][columna] == "[M]" || (fila - 1 >= 0 && matrizO[fila - 1][columna] == "[M]"))) { imprimirMatriz(matrizO) colocarMosca(matrizO) println("casi pero no") }else if ((fila + 1 < matrizO.size || fila -1< 0 && columna - 1 > 0) || (columna + 1 < matrizO.size && matrizO[fila - 1][columna - 1] == "[M]" && matrizO[fila - 1][columna + 1] == "[M]")) { imprimirMatriz(matrizO) colocarMosca(matrizO) println("casi pero no") } } fun imprimirMatriz(matrizO: Array<Array<String>>) { for (i in matrizO.indices){ for (j in matrizO.indices){ print(matrizO[i][j]) } println() } } fun muerta(matrizO: Array<Array<String>>, columna: Int, fila: Int):Boolean { var muerte = true if (matrizO[fila][columna] == "[M]"){ muerte = false } return muerte }
ejercicioMatriz/ejercicio11/mosca/src/main/kotlin/Main.kt
1945106446
fun main(args: Array<String>) { val matrizOriginal = arrayOf( arrayOf(1,2,3,4), arrayOf(5,6,7,8), arrayOf(9,10,11,12), arrayOf(13,14,15,16)) val matrizNoventa = Array(5) {IntArray(5)} original(matrizOriginal) println() noventa(matrizOriginal, matrizNoventa) } fun original(matrizOriginal: Array<Array<Int>>) { for (i in matrizOriginal.indices){ for (j in matrizOriginal.indices){ print("[${matrizOriginal[i][j]}]") } println() } } fun noventa(matrizOriginal: Array<Array<Int>>, matrizNoventa: Array<IntArray>) { for (i in matrizOriginal.indices){ for (j in (matrizOriginal.size -1 downTo 0)){ matrizNoventa[i][j] = matrizOriginal[j][i] print("[${matrizNoventa[i][j]}]") } println() } }
ejercicioMatriz/ejercicio08/noventa-grados/src/main/kotlin/Main.kt
2919107204
fun main(args: Array<String>) { val matrizO = arrayOf(arrayOf(5,1,3), arrayOf(1,8,2), arrayOf(3,2,59)) val matrizT = Array (3) {IntArray(3)} transponer(matrizO, matrizT) prinMatrizO(matrizT) println() prinMatrizT(matrizO) println() contador(matrizT,matrizO) } fun prinMatrizT(matrizO: Array<Array<Int>>) { for (i in matrizO.indices){ for (j in matrizO.indices){ print("[${matrizO[i][j]}]") } println() } } fun contador(matrizT: Array<IntArray>, matrizO: Array<Array<Int>>) { var multiplicacion = matrizO.size * matrizT.size if (matrizO[0][0]==matrizT[matrizT.size-1][matrizT.size -1] && comparation(matrizT, matrizO) == multiplicacion){ println("es simetrica") }else{ println("no es simetrica") } } fun comparation(matrizT: Array<IntArray>, matrizO: Array<Array<Int>>): Int { var contador = 0 var descontador = 0 for (i in matrizT.indices){ for (j in matrizO.indices){ if (matrizT[i][j] == matrizO[i][j]){ contador++ } } } return contador } fun prinMatrizO(matrizT: Array<IntArray>) { for (i in matrizT.indices){ for (j in matrizT.indices){ print("[${matrizT[i][j]}]") } println() } } fun transponer(matrizO: Array<Array<Int>>, matrizT: Array<IntArray>) { for (i in matrizO.indices){ for (j in matrizO.indices){ matrizT[i][j]=matrizO[j][i] } } }
ejercicioMatriz/ejercicio08/simetrica/src/main/kotlin/Main.kt
579254175
fun main(args: Array<String>) { val matriz = arrayOf(arrayOf(11,12,13), arrayOf(21,22,23), arrayOf(31,32,33)) val vector = IntArray(3) for (i in matriz.indices){ for (j in matriz.indices){ print("-[${matriz[i][j]}]-") } println() } colocar(matriz, vector) println() println(" ${suma(matriz)}") } fun suma (matriz: Array<Array<Int>>): Int{ var filaUno = 0 var filaDos = 0 var filaTres = 0 for (i in matriz.indices){ for (j in matriz.indices){ if (matriz[i][j] == matriz[0][j] && matriz[i][j] > filaUno ){ filaUno = matriz[i][j] } if (matriz[i][j] == matriz[1][j] && matriz[i][j] > filaDos ){ filaDos = matriz[i][j] } if (matriz[i][j] == matriz[2][j] && matriz[i][j] > filaTres ){ filaTres = matriz[i][j] } } } var final = filaUno + filaDos + filaTres return final /3 } fun colocar (matriz: Array<Array<Int>>, vector: IntArray){ for (i in matriz.indices){ for (j in matriz.indices){ if (matriz[i][j] == matriz[0][j] && matriz[i][j] > vector[0] ){ vector[0] = matriz[i][j] } if (matriz[i][j] == matriz[1][j] && matriz[i][j] > vector[1] ){ vector[1] = matriz[i][j] } if (matriz[i][j] == matriz[2][j] && matriz[i][j] > vector[2] ){ vector[2] = matriz[i][j] } } } for (i in vector.indices){ print("-[${vector[i]}]-") } }
ejercicioMatriz/ejercicio01/suma/src/main/kotlin/Main.kt
2577872367
const val MAX = 5 fun main(args: Array<String>) { val matrizOriginaral = arrayOf(arrayOf(1,2,3,4,5), arrayOf(6,7,8,9,10), arrayOf(11,12,13,14,15), arrayOf(16,17,18,19,20), arrayOf(21,22,23,24,25)) val matrizEscritura = Array(MAX) {IntArray(MAX)} imprimir(matrizOriginaral) println() clonar(matrizOriginaral,matrizEscritura) } fun imprimir(matrizLectura: Array<Array<Int>>) { for (i in matrizLectura.indices){ for (j in matrizLectura.indices){ print("[${matrizLectura[i][j]}]") } println() } } fun clonar(matrizLectura: Array<Array<Int>>, matrizEscritura: Array<IntArray>) { for (i in matrizEscritura.indices){ for (j in matrizEscritura.indices){ matrizEscritura[i][j]= matrizLectura[j][i] print("[${matrizEscritura[i][j]}]") } println() } }
ejercicioMatriz/ejercicio07/noventa/src/main/kotlin/Main.kt
768218233
package org.example fun main() { val matriz = arrayOf( arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]"), arrayOf("[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]","[ ]")) imprimir(matriz) var pieza = "" var f = 0 var c= 0 println("que piezas quieres colocar") pieza = readln().toString() println("en que fila lo quieres poner") f = readln().toIntOrNull()?:0 println("en que columna lo quieres poner") c = readln().toIntOrNull()?:0 when (pieza){ "dama" -> dama(f,c, matriz) "torre" -> torre(f,c, matriz) "caballo" -> caballo(f,c, matriz) "alfi" -> alfi(f,c, matriz) } } fun alfi(f: Int, c: Int, matriz: Array<Array<String>>) { matriz[f][c] = " A " // diagonalizq (f,c,matriz) diagonaldrc(f,c,matriz) imprimir(matriz) } fun caballo(f: Int, c: Int, matriz: Array<Array<String>>) { matriz[f][c] = "[C]" imprimir(matriz) saltar(f,c,matriz) imprimir(matriz) } fun saltar(f: Int, c: Int, matriz: Array<Array<String>>) { var i = f var j = c if(i+2 < matriz.size-1 && j+2 < matriz.size && j>0){ matriz[i+2][j+1]= "[*]" matriz[i+2][j-1]= "[*]" }else if (i+2 < matriz.size-1 && j+2 < matriz.size-1 ){ matriz[i+2][j+1]= "[*]" }else if (i+2 < matriz.size-1 && j >0){ matriz[i+2][j-1]= "[*]" } if (i > 0 && j+2 < matriz.size-1 && j>0){ matriz[i-2][j-1]= "[*]" matriz[i-2][j+1]= "[*]" }else if (i > 0 && j+2 < matriz.size-1){ matriz[i-2][j+1]= "[*]" }else if (i > 0 && j > 0){ matriz[i-2][j-1]= "[*]" } if (j+2 < matriz.size-1 && i+2 < matriz.size-1 && i>0){ matriz[i+1][j+2]= "[*]" matriz[i-1][j+2]= "[*]" }else if (j+2 < matriz.size-1 && i+2 < matriz.size-1){ matriz[i+1][j+2]= "[*]" }else if (j < matriz.size-1 && i>0){ matriz[i-1][j+2]= "[*]" } if (j > 0 && i+2 < matriz.size-1 && i>0){ matriz[i+1][j-2]= "[*]" matriz[i-1][j-2]= "[*]" }else if (j > 0 && i+2 < matriz.size-1){ matriz[i+1][j-2]= "[*]" }else if (j<0 && i>0){ matriz[i-1][j-2]= "[*]" } } fun torre(f: Int, c: Int, matriz: Array<Array<String>>) { matriz[f][c] = " T " imprimir(matriz) columna(f,c,matriz) fila(f,c,matriz) } fun dama(f: Int, c: Int, matriz: Array<Array<String>>) { println() matriz[f][c] = "[D]" columna(f,c,matriz) fila(f,c,matriz) diagonalizq (f,c,matriz) diagonaldrc(f,c,matriz) imprimir(matriz) } fun diagonaldrc(f: Int, c: Int, matriz: Array<Array<String>>) { var menosfila = f var masfila = f var mascolumna = c var menoscolumna = c for (i in matriz.indices){ for (j in matriz.indices){ if (menosfila < matriz.size-1 && menoscolumna > 0){ menosfila++ menoscolumna-- matriz[menosfila][menoscolumna] = "[*]" } if (masfila > 0 && mascolumna < matriz.size-1 ){ masfila-- mascolumna++ matriz[masfila][mascolumna]= "[*]" } } } } fun diagonalizq(f: Int, c: Int, matriz: Array<Array<String>>) { var menosfila = f var masfila = f var mascolumna = c var menoscolumna = c for (i in matriz.indices){ for (j in matriz.indices){ if (menosfila > 0 && menoscolumna > 0){ menosfila-- menoscolumna-- matriz[menosfila][menoscolumna] = "[*]" } if (masfila < matriz.size-1 && mascolumna < matriz.size-1 ){ masfila++ mascolumna++ matriz[masfila][mascolumna]= "[*]" } } } } fun fila(f: Int, c: Int, matriz: Array<Array<String>>) { var menos = f var mas = f for (i in matriz.indices){ for (j in matriz.indices){ if (menos > 0){ menos-- matriz[menos][c]= "[*]" } if (mas < matriz.size-1 ){ mas++ matriz[mas][c]= "[*]" } } } } fun columna(f: Int, c: Int, matriz: Array<Array<String>>) { var menos = c var mas = c for (i in matriz.indices){ for (j in matriz.indices){ if (menos > 0){ menos-- matriz[f][menos]= "[*]" } if (mas < matriz.size-1 ){ mas++ matriz[f][mas]= "[*]" } } } } fun imprimir(matriz: Array<Array<String>>) { for (i in matriz.indices){ for (j in matriz.indices){ print(matriz[i][j]) } println() } println() }
ejercicioMatriz/ejercicio12/untitled/src/main/kotlin/Main.kt
692379581
package com.example.arventurepath 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.arventurepath", appContext.packageName) } }
ARventurePathAndroid/app/src/androidTest/java/com/example/arventurepath/ExampleInstrumentedTest.kt
2280312568
package com.example.arventurepath 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) } }
ARventurePathAndroid/app/src/test/java/com/example/arventurepath/ExampleUnitTest.kt
1662944073
package com.example.arventurepath.ui.detail_arventure_fragment import android.Manifest import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.arventurepath.R import com.example.arventurepath.databinding.FragmentDetailArventureBinding import com.example.arventurepath.utils.Constants.REQUEST_PERMISSION import kotlinx.coroutines.launch class DetailArventureFragment : Fragment() { private lateinit var binding: FragmentDetailArventureBinding private val args: DetailArventureFragmentArgs by navArgs() private val viewModel = DetailArventureViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentDetailArventureBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeViewModel() viewModel.getArventureDetail(args.idArventure) binding.button.setOnClickListener{ checkPermissions() } } private fun observeViewModel() { viewLifecycleOwner.lifecycleScope.launch { viewModel.arventureDetail.collect { binding.arventureTitle.text = it.name.uppercase() binding.summaryArventure.text = it.summary binding.distanceArventure.text = it.distance binding.minutesArventure.text = it.time binding.originArventure.text = it.origin binding.storyNameArventure.text = it.nameStory Glide.with(requireContext()) .load("http://abp-politecnics.com/2024/DAM01/filesToServer/imgStory/" + it.img) .error(R.drawable.aventura2) .apply(RequestOptions().centerCrop()) .into(binding.imgArventure) } } viewLifecycleOwner.lifecycleScope.launch { viewModel.loading.collect { isLoading -> if (!isLoading) { binding.progressBar.visibility = View.GONE binding.linearImg.visibility = View.VISIBLE binding.linearSummary.visibility = View.VISIBLE binding.linearTitle.visibility = View.VISIBLE } } } } private fun checkPermissions() { val fineLocationPermissionGranted = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED val coarseLocationPermissionGranted = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED val cameraPermissionGranted = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED val activityRecognitionPermissionGranted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACTIVITY_RECOGNITION ) == PackageManager.PERMISSION_GRANTED } else { // TODO: Revisar esto, que puse un true por poner algo true } if (!fineLocationPermissionGranted || !coarseLocationPermissionGranted || !cameraPermissionGranted || !activityRecognitionPermissionGranted ) { // Al menos uno de los permisos no está concedido requestPermissions() } else { // Ambos permisos están concedidos, puedes acceder a lo que sea findNavController().navigate( DetailArventureFragmentDirections.actionDetailArventureFragmentToInGameFragment( idUser = args.idUser, idArventure = args.idArventure ) ) } } private fun requestPermissions() { val fineLocationPermissionGranted = ActivityCompat.shouldShowRequestPermissionRationale( requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION ) val storagePermissionGranted = ActivityCompat.shouldShowRequestPermissionRationale( requireActivity(), Manifest.permission.ACCESS_COARSE_LOCATION ) val cameraPermissionGranted = ActivityCompat.shouldShowRequestPermissionRationale( requireActivity(), Manifest.permission.CAMERA ) val activityRecognitionPermissionGranted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { ActivityCompat.shouldShowRequestPermissionRationale( requireActivity(), Manifest.permission.ACTIVITY_RECOGNITION ) } else { // TODO: Revisar esto, que puse un true por poner algo true } if (fineLocationPermissionGranted || storagePermissionGranted || cameraPermissionGranted || activityRecognitionPermissionGranted ) { // El usuario ya ha rechazado los permisos Toast.makeText( requireContext(), "Ya has rechazado los permisos. Debes cambiarlos desde los ajustes.", Toast.LENGTH_LONG ).show() } else { // Pedir permisos ActivityCompat.requestPermissions( requireActivity(), arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.CAMERA, Manifest.permission.ACTIVITY_RECOGNITION ), REQUEST_PERMISSION ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_PERMISSION) { if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) { // Ambos permisos concedidos, puedes acceder a lo que sea findNavController().navigate( DetailArventureFragmentDirections.actionDetailArventureFragmentToInGameFragment( idUser = args.idUser, idArventure = args.idArventure ) ) } else { Toast.makeText( requireContext(), "Permisos rechazados por primera vez", Toast.LENGTH_LONG ).show() } } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/detail_arventure_fragment/DetailArventureFragment.kt
510678241
package com.example.arventurepath.ui.detail_arventure_fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.arventurepath.data.models.ArventureDetail import com.example.arventurepath.data.remote.DataProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class DetailArventureViewModel : ViewModel() { private val _arventureDetail = MutableStateFlow(ArventureDetail()) val arventureDetail: StateFlow<ArventureDetail> = _arventureDetail private val _loading = MutableStateFlow(true) val loading: StateFlow<Boolean> = _loading fun getArventureDetail(idArventure: Int) { viewModelScope.launch(Dispatchers.IO) { val deferred = async { _arventureDetail.emit(DataProvider.getArventureDetail(idArventure)) } deferred.await() _loading.emit(false) } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/detail_arventure_fragment/DetailArventureViewModel.kt
1532546825
package com.example.arventurepath.ui.login_fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.example.arventurepath.R import com.example.arventurepath.databinding.FragmentLoginBinding import kotlinx.coroutines.launch class LoginFragment : Fragment() { private lateinit var binding: FragmentLoginBinding private var register: Boolean = false private val viewModel = LoginViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentLoginBinding.inflate(inflater, container, false) //launchExternalApk("com.DefaultCompany.Intento1") return binding.root } /*private val contractRA: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { // Aquí puedes manejar el resultado de la grabación de audio val data: Intent? = result.data // Procesar los datos si es necesario } else { // Si la acción se cancela o falla, aquí puedes manejarlo } } private fun launchExternalApk(packageName: String) { val intent = requireContext().packageManager.getLaunchIntentForPackage(packageName) intent?.let { contractRA.launch(it) } ?: run { // Manejar el caso en el que no se pueda lanzar la actividad Toast.makeText(requireContext(), "No se pudo iniciar la aplicación", Toast.LENGTH_SHORT).show() } }*/ /*private fun startLikeRaceQuiz() { val packageName = "com.DefaultCompany.Intento1" val packageManager = requireActivity().packageManager val launchIntent = packageManager.getLaunchIntentForPackage(packageName) if(launchIntent != null){ startActivity(launchIntent) } }*/ /*private fun runApk(apkResourceId: Int) { val apkInputStream = resources.openRawResource(apkResourceId) val apkFile = File(requireContext().filesDir, "temp.apk") // Guarda temporalmente la APK apkInputStream.copyTo(apkFile.outputStream()) val apkUri = FileProvider.getUriForFile(requireContext(), "${requireContext().packageName}.provider", apkFile) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(apkUri, "application/vnd.android.package-archive") addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // Para abrir en una nueva tarea } startActivity(intent) }*/ /*fun getPackageNameFromApk(apkResourceId: Int): String? { val packageManager = requireContext().packageManager val packageName: String? val packageArchiveInfo = packageManager.getPackageArchiveInfo( "android.resource://" + requireContext().packageName + "/" + apkResourceId, PackageManager.GET_META_DATA ) if (packageArchiveInfo != null) { packageName = packageArchiveInfo.packageName } else { packageName = null } return packageName }*/ /*fun launchUnityApp(view: View) { val unityPackageUri = Uri.parse("android.resource://" + packageName + "/" + R.raw.your_unity_apk) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(unityPackageUri, "application/vnd.android.package-archive") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } startActivity(intent) }*/ /* private fun tryingApk() { val apkInputStream = resources.openRawResource(R.raw.apk_ra) val apkFile = File(requireContext().filesDir, "apk_ra") apkInputStream.copyTo(apkFile.outputStream()) val apkUri = FileProvider.getUriForFile(requireContext(), "com.example.arventurepath.ui.login_fragment.LoginFragment.FileProvider", apkFile) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(apkUri, "application/vnd.android.package-archive") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } startActivity(intent) }*/ /*private fun launchInstalledApp(packageName: String) { val packageManager = requireActivity().packageManager val intent = packageManager.getLaunchIntentForPackage(packageName) if (intent != null) { intent.addCategory(Intent.CATEGORY_LAUNCHER) startActivity(intent) } else { // La aplicación no está instalada Toast.makeText(requireContext(), "La aplicación no está instalada", Toast.LENGTH_SHORT).show() } }*/ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.getListUsers() registerUser() binding.buttonLogin.setOnClickListener { if (!isEditTextBlank()) { if (register) { if (!viewModel.isEmailRegistered(binding.editTextEmail.text.toString())) { if(binding.editTextPasswordRepeat.text.toString() == binding.editTextPassword.text.toString()){ val emailUser = binding.editTextEmail.text.toString() val password = binding.editTextPassword.text.toString() if (verifyEmail(emailUser)){ if (verifyPassword(password)){ val passwordEncrypted = viewModel.hashPassword(password) hideElements() viewModel.registerUser(emailUser,passwordEncrypted) } } }else{ Toast.makeText(context,"Las contraseñas no coinciden.",Toast.LENGTH_SHORT).show() } }else{ Toast.makeText(context,"Este email ya está registrado.",Toast.LENGTH_SHORT).show() } }else{ val emailUser = binding.editTextEmail.text.toString() val password = binding.editTextPassword.text.toString() if(viewModel.isEmailRegistered(emailUser)){ val userId = viewModel.userExist(emailUser,password) if (userId != -1){ hideElements() findNavController().navigate( LoginFragmentDirections.actionLoginFragmentToListArventureFragment3(idUser = userId) ) }else{ Toast.makeText(context,"Contraseña incorrecta.",Toast.LENGTH_SHORT).show() } }else{ Toast.makeText(context,"Email no encontrado.",Toast.LENGTH_SHORT).show() } } }else{ Toast.makeText(context,"Rellene todos los campos.",Toast.LENGTH_SHORT).show() } } binding.textViewRegister.setOnClickListener { binding.editTextEmail.setText("") binding.editTextPassword.setText("") binding.editTextPasswordRepeat.setText("") if (!register){ binding.editTextPasswordRepeat.visibility = View.VISIBLE binding.textViewRegister.text = getString(R.string.noregisterText) binding.buttonLogin.text = getString(R.string.register) register = true }else{ binding.editTextPasswordRepeat.visibility = View.GONE binding.textViewRegister.text = getString(R.string.registerText) binding.buttonLogin.text = getString(R.string.login) register = false } } } private fun registerUser(){ viewLifecycleOwner.lifecycleScope.launch { viewModel.idUser.collect { idRegisterUser -> if (idRegisterUser != -1) { findNavController().navigate( LoginFragmentDirections.actionLoginFragmentToTutorialFragment(idUser = idRegisterUser) ) } } } viewLifecycleOwner.lifecycleScope.launch { viewModel.loading.collect { isLoading -> if (!isLoading) { binding.progressBar.visibility = View.GONE } } } } private fun hideElements(){ binding.viewLogin.visibility = View.GONE binding.editTextPassword.visibility = View.GONE binding.editTextEmail.visibility = View.GONE binding.editTextPasswordRepeat.visibility = View.GONE binding.textViewRegister.visibility = View.GONE binding.imageViewEmail.visibility = View.GONE binding.imageViewLock.visibility = View.GONE binding.buttonLogin.isEnabled = false } private fun verifyEmail(mail: String): Boolean { // Patrón de expresión regular para verificar el correo electrónico val mailPattern = Regex("^[\\w\\.-]+@[a-zA-Z0-9\\.-]+\\.[a-zA-Z]{2,}$") // Si es válido, devolvemos true return if (mailPattern.matches(mail)) { true } else { // Si no es válido, mostramos un Toast con el mensaje correspondiente val errorMessage = "El formato del correo electrónico es incorrecto." Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show() false } } private fun verifyPassword(password: String): Boolean { val minLength = 8 // Cambia este valor según tu política val allowedCharacters = Regex("^[a-zA-Z0-9.!@#\$%^&*()_+=-]*\$") // Caracteres permitidos: letras, números, y algunos especiales // Verificar longitud mínima if (password.length < minLength) { Toast.makeText(context,"La contraseña debe tener al menos $minLength caracteres.",Toast.LENGTH_SHORT).show() return false } // Verificar caracteres permitidos if (!password.matches(allowedCharacters)) { Toast.makeText(context,"La contraseña contiene caracteres no permitidos.",Toast.LENGTH_SHORT).show() return false } // Verificar al menos un carácter especial val specialCharacters = Regex("[.!@#\$%^&*()_+=-]") if (!password.contains(specialCharacters)) { Toast.makeText(context,"La contraseña debe contener al menos un carácter especial: !@#\$%^&*()_+=-",Toast.LENGTH_SHORT).show() return false } // Si pasa todas las verificaciones, la contraseña es válida return true } private fun isEditTextBlank():Boolean{ if (binding.editTextEmail.text.toString() == ""){ return true } if (binding.editTextPassword.text.toString() == ""){ return true } if (register){ if (binding.editTextPasswordRepeat.text.toString() == ""){ return true } } return false } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/login_fragment/LoginFragment.kt
2256548380
package com.example.arventurepath.ui.login_fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.arventurepath.data.models.UserToRegister import com.example.arventurepath.data.remote.DataProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import org.mindrot.jbcrypt.BCrypt class LoginViewModel: ViewModel() { private var listUsers: List<UserToRegister> = listOf() private val _idUser = MutableStateFlow(-1) val idUser: StateFlow<Int> = _idUser private val _loading = MutableStateFlow(true) val loading: StateFlow<Boolean> = _loading fun getListUsers(){ viewModelScope.launch(Dispatchers.IO) { listUsers = DataProvider.getListUsers() } } fun isEmailRegistered(mail: String): Boolean { for (user in listUsers) { if (mail == user.mail) { return true } } return false } fun hashPassword(password: String): String { return BCrypt.hashpw(password, BCrypt.gensalt()) } fun userExist(mail: String, password: String): Int{ for (user in listUsers) { if (mail == user.mail && BCrypt.checkpw(password,user.passwd)) { return user.id } } return -1 } fun registerUser(mail: String, hashPass: String){ val userRegister = UserToRegister(mail = mail, passwd = hashPass) viewModelScope.launch(Dispatchers.IO) { val valor = DataProvider.registerUser(userRegister) val deferred = async{_idUser.emit(valor.id) } deferred.await() _loading.emit(false) } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/login_fragment/LoginViewModel.kt
65851957
package com.example.arventurepath.ui.main_activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.arventurepath.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/main_activity/MainActivity.kt
3460341595
package com.example.arventurepath.ui.tutorial_fragment import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.MediaController import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.example.arventurepath.R import com.example.arventurepath.databinding.FragmentTutorialBinding class TutorialFragment : Fragment() { private lateinit var binding: FragmentTutorialBinding private val args: TutorialFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentTutorialBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val videoPath = "android.resource://" + requireContext().packageName + "/" + R.raw.tutorial_arventure_path val videoUri = Uri.parse(videoPath) val mediaController = MediaController(requireContext()) mediaController.setAnchorView(binding.videoViewTuto) binding.videoViewTuto.setMediaController(mediaController) binding.videoViewTuto.setVideoURI(videoUri) binding.videoViewTuto.start() binding.buttonSkip.setOnClickListener{ findNavController().navigate( TutorialFragmentDirections.actionTutorialFragmentToListArventureFragment3(idUser = args.idUser) ) } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/tutorial_fragment/TutorialFragment.kt
2524605172
package com.example.arventurepath.ui.in_game_fragment import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.arventurepath.data.models.Achievement import com.example.arventurepath.data.models.ArventureToPlay import com.example.arventurepath.data.models.ListAchievements import com.example.arventurepath.data.models.Stop import com.example.arventurepath.data.models.StoryFragment import com.example.arventurepath.data.models.UserToPlay import com.example.arventurepath.data.remote.DataProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class InGameViewModel() : ViewModel() { private val _arventureDetail = MutableStateFlow(ArventureToPlay()) val arventureDetail: StateFlow<ArventureToPlay> = _arventureDetail private val _loading = MutableStateFlow(true) val loading: StateFlow<Boolean> = _loading private val _stop = MutableSharedFlow<Stop>() val stop: SharedFlow<Stop> = _stop private val _storyFragment = MutableSharedFlow<StoryFragment>() val storyFragment: SharedFlow<StoryFragment> = _storyFragment private val _win = MutableSharedFlow<ListAchievements>() val win: SharedFlow<ListAchievements> = _win private val stops = mutableListOf<Stop>() private val storyFragments = mutableListOf<StoryFragment>() private var achievements = ListAchievements(mutableListOf()) private val achievementsToEarn = mutableListOf<Achievement>() private val _achievementToShow = MutableSharedFlow<Achievement>() val achievementToShow: SharedFlow<Achievement> = _achievementToShow private var _user = UserToPlay() fun getArventureDetailUser(idArventure: Int,idUser: Int) { viewModelScope.launch(Dispatchers.IO) { val deferred = async { _arventureDetail.emit(DataProvider.getArventureToPlay(idArventure)) stops.addAll(_arventureDetail.value.route.stops) storyFragments.addAll(_arventureDetail.value.story.storyFragments) _user = DataProvider.getUserById(idUser) } deferred.await() getListAchievements() _loading.emit(false) } } private fun getListAchievements() { viewModelScope.launch(Dispatchers.IO) { achievementsToEarn.addAll(DataProvider.getListAchievements() as MutableList<Achievement>) achievementsToEarn.removeAll { achievementEarn -> _user.achievement.any { achievementUser -> achievementEarn.name == achievementUser.name } } } } fun getStoryFragment() { viewModelScope.launch { if (storyFragments.isNotEmpty()) { _storyFragment.emit(storyFragments[0]) } } } fun removeStoryFragment() { if (storyFragments.isNotEmpty()) { storyFragments.removeAt(0) } } fun getStop() { viewModelScope.launch { if (stops.isNotEmpty()) { _stop.emit(stops[0]) } else { _user.achievement.add(_arventureDetail.value.achievement) achievements.achievements.add(_arventureDetail.value.achievement) DataProvider.updateUser(_user.id, _user) _win.emit(achievements) } } } fun removeStop() { if (stops.isNotEmpty()) { stops.removeAt(0) } } fun earnTimeAchievement() { _user.achievement.addAll(achievementsToEarn.filter { it.name == "Juega durante 5 minutos" }) achievements.achievements.addAll(achievementsToEarn.filter { it.name == "Juega durante 5 minutos" }) viewModelScope.launch(Dispatchers.IO) { _achievementToShow.emit(achievements.achievements.last()) } } fun earn100StepsAchievement() { _user.achievement.addAll(achievementsToEarn.filter { it.name == "Recorre 100 pasos" }) achievements.achievements.addAll(achievementsToEarn.filter { it.name == "Recorre 100 pasos" }) viewModelScope.launch(Dispatchers.IO) { _achievementToShow.emit(achievements.achievements.last()) DataProvider.updateUser(_user.id, _user) } } fun earn500StepsAchievement() { _user.achievement.addAll(achievementsToEarn.filter { it.name == "Recorre 500 pasos" }) achievements.achievements.addAll(achievementsToEarn.filter { it.name == "Recorre 500 pasos" }) viewModelScope.launch(Dispatchers.IO) { _achievementToShow.emit(achievements.achievements.last()) } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/in_game_fragment/InGameViewModel.kt
2185023622
package com.example.arventurepath.ui.in_game_fragment import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.location.Location import android.media.MediaPlayer import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.FileProvider import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.arventurepath.R import com.example.arventurepath.data.models.Happening import com.example.arventurepath.data.models.Stop import com.example.arventurepath.databinding.FragmentInGameBinding import com.example.arventurepath.ui.detail_arventure_fragment.DetailArventureFragmentArgs import com.example.arventurepath.utils.Constants import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import kotlinx.coroutines.launch import java.io.File import kotlin.random.Random class InGameFragment : Fragment(), OnMapReadyCallback, SensorEventListener { private lateinit var binding: FragmentInGameBinding private val args: DetailArventureFragmentArgs by navArgs() private var totalSeconds: Int = 0 private lateinit var handlerTime: Handler private lateinit var handlerHappening: Handler private var secondsHappening: Int = 0 private val viewModel = InGameViewModel() private lateinit var map: GoogleMap private lateinit var nextStop: Stop private lateinit var destinyMarker: Marker private lateinit var fusedLocationClient: FusedLocationProviderClient private var sensorManager: SensorManager? = null private var running = false private var totalSteps = 0f private var i = 1 private var isFirstStop = true private var isOnStop = false private var randomSecondHappening = 0 private var happenings: MutableList<Happening> = arrayListOf() private var showingHappening = false private lateinit var mediaPlayer: MediaPlayer private var audioURL = "" private var currentSteps = 0 private var startButtonPressed = false private var choiceRA = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentInGameBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //Timer tiempo handlerTime = Handler(Looper.getMainLooper()) handlerHappening = Handler(Looper.getMainLooper()) //Reproductor Audio mediaPlayer = MediaPlayer() setMap() viewModel.getArventureDetailUser(args.idArventure, args.idUser) observeViewModel() //startTimer() binding.buttonStart.setOnClickListener { // TODO: inicializar el contador de pasos //isFirstStop = false //Contador de pasos sensorManager = requireContext().getSystemService(Context.SENSOR_SERVICE) as SensorManager val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) if (stepSensor == null) { // This will give a toast message to the user if there is no sensor in the device Toast.makeText( requireContext(), "No sensor detected on this device", Toast.LENGTH_SHORT ).show() } else { sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI) } startTimer() viewModel.getStoryFragment() binding.llAchievement.setOnClickListener { it.visibility = View.GONE } with(binding) { nextStopText.visibility = View.VISIBLE nextStopValueText.visibility = View.VISIBLE timeText.visibility = View.VISIBLE timeValueText.visibility = View.VISIBLE stepsText.visibility = View.VISIBLE stepsValueText.visibility = View.VISIBLE buttonStart.visibility = View.GONE tvGoToStart.visibility = View.GONE } } binding.tvTxtInGame.setOnClickListener { if (!isFirstStop) { when (choiceRA) { 0 -> { launchExternalApk(Constants.FENIX_PACKAGE) choiceRA++ } 1 -> { launchExternalApk(Constants.DRAGON_PACKAGE) choiceRA++ } 2 -> { launchExternalApk(Constants.ROBOT_PACKAGE) choiceRA++ } else -> { choiceRA = 0 destinyMarker.remove() viewModel.removeStop() viewModel.getStop() binding.tvTxtInGame.visibility = View.GONE viewModel.removeStoryFragment() } } } else { destinyMarker.remove() viewModel.removeStop() viewModel.getStop() it.visibility = View.GONE viewModel.removeStoryFragment() } isFirstStop = false /*destinyMarker.remove() viewModel.removeStop() viewModel.getStop() it.visibility = View.GONE viewModel.removeStoryFragment()*/ } startCheckMarkerTimer() binding.textHappening.setOnClickListener { restartHappening() } binding.imgHappening.setOnClickListener { restartHappening() } } private fun restartHappening() { binding.imgHappening.visibility = View.GONE binding.textHappening.visibility = View.GONE showingHappening = false randomSecondHappening = 0 secondsHappening = 0 } override fun onSensorChanged(event: SensorEvent?) { if (running) { // i = 2 totalSteps = event!!.values[0] // 11 val steps = event.values[0] + i // 13 // Current steps are calculated by taking the difference of total steps // and previous steps currentSteps = steps.toInt() - totalSteps.toInt() // 13 - 11 = 2 if (currentSteps == 100) { viewModel.earn100StepsAchievement() } if (currentSteps == 500) { viewModel.earn500StepsAchievement() } // It will show the current steps to the user binding.stepsValueText.text = ("$currentSteps") i++ } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { } override fun onResume() { super.onResume() running = true // Returns the number of steps taken by the user since the last reboot while activated // This sensor requires permission android.permission.ACTIVITY_RECOGNITION. // So don't forget to add the following permission in AndroidManifest.xml present in manifest folder of the app. val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) if (stepSensor == null) { // This will give a toast message to the user if there is no sensor in the device //Toast.makeText(requireContext(), "No sensor detected on this device", Toast.LENGTH_SHORT).show() } else { // Rate suitable for the user interface sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI) } } private fun startTimer() { // Ejecutar un Runnable cada segundo para contar los segundos handlerTime.post(object : Runnable { override fun run() { // Incrementar los segundos totalSeconds++ // Actualizar la UI con los segundos transcurridos en formato de horas, minutos y segundos updateUI() if (totalSeconds == 300) { viewModel.earnTimeAchievement() } // Ejecutar este Runnable nuevamente después de 1 segundo handlerTime.postDelayed(this, 1000) } }) handlerHappening.post(object : Runnable { override fun run() { if (randomSecondHappening == 0) { randomSecondHappening = Random.nextInt(30, 120) } if (!showingHappening) { randomHappening() } if (secondsHappening - randomSecondHappening >= 11) { restartHappening() } secondsHappening += 5 handlerHappening.postDelayed(this, 5000) } }) } private fun randomHappening() { if (!isOnStop) { if (secondsHappening >= randomSecondHappening) { if (happenings.isNotEmpty()) { showingHappening = true val randomHappeningNum = Random.nextInt(happenings.size) val selectedHappening = happenings[randomHappeningNum] when (selectedHappening.type) { "text" -> { binding.textHappening.visibility = View.VISIBLE binding.textHappening.text = selectedHappening.text } "image" -> { binding.imgHappening.visibility = View.VISIBLE Glide.with(requireContext()) .load("http://abp-politecnics.com/2024/DAM01/filesToServer/imgHappening/${selectedHappening.img}") .error(R.drawable.aventura2) .apply(RequestOptions().centerCrop()) .into(binding.imgHappening) } "audio" -> { audioURL = "http://abp-politecnics.com/2024/DAM01/filesToServer/audioHappening/${selectedHappening.img}" try { mediaPlayer.stop() mediaPlayer.release() mediaPlayer = MediaPlayer() mediaPlayer.setDataSource(audioURL) mediaPlayer.prepare() mediaPlayer.start() } catch (e: Exception) { Toast.makeText( requireContext(), "Ha habido un problema al intentar reproducir el audio", Toast.LENGTH_LONG ).show() } Toast.makeText( requireContext(), "Audio en reproducción", Toast.LENGTH_LONG ).show() } } // Remover el happening seleccionado para que no se vuelva a utilizar happenings.removeAt(randomHappeningNum) } } } } private fun updateUI() { val hours = totalSeconds / 3600 val minutes = (totalSeconds % 3600) / 60 val seconds = totalSeconds % 60 val timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds) binding.timeValueText.text = timeString } private fun observeViewModel() { viewLifecycleOwner.lifecycleScope.launch { viewModel.arventureDetail.collect { binding.timeValueText.text = "0" binding.stepsValueText.text = "0" binding.arventureTitle.text = it.name.uppercase() happenings = viewModel.arventureDetail.value.happenings.toMutableList() } } viewLifecycleOwner.lifecycleScope.launch { viewModel.stop.collect { binding.nextStopValueText.text = it.name nextStop = it createNextStopMarker() } } viewLifecycleOwner.lifecycleScope.launch { viewModel.storyFragment.collect { binding.tvTxtInGame.visibility = View.VISIBLE binding.tvTxtInGame.text = it.content } } viewLifecycleOwner.lifecycleScope.launch { viewModel.achievementToShow.collect { // TODO: mostrar aquí el logro binding.llAchievement.visibility = View.VISIBLE binding.tvAchievementContent.text = it.name Glide.with(requireContext()) .load("http://abp-politecnics.com/2024/DAM01/filesToServer/imgAchievement/${it.img}") .error(R.drawable.aventura2) .apply(RequestOptions().centerCrop()) .into(binding.imgAchievement) } } viewLifecycleOwner.lifecycleScope.launch { viewModel.win.collect { findNavController().navigate( InGameFragmentDirections.actionInGameFragmentToScoreFragment2( currentSteps, it, args.idUser, args.idArventure, totalSeconds ) ) } } } private fun setMap() { // Inicializar el cliente de ubicación fusionada fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity()) binding.mapInGame.getFragment<SupportMapFragment>().getMapAsync(this) } @SuppressLint("MissingPermission") override fun onMapReady(googleMap: GoogleMap) { map = googleMap viewModel.getStop() // Habilitar el botón "Mi ubicación" en el mapa map.isMyLocationEnabled = true } private fun startCheckMarkerTimer() { // Ejecutar un Runnable cada segundo para contar los segundos handlerTime.post(object : Runnable { override fun run() { // Incrementar los segundos checkIfComeToMark() // Actualizar la UI con los segundos transcurridos en formato de horas, minutos y segundos updateUI() // Ejecutar este Runnable nuevamente después de 1 segundo handlerTime.postDelayed(this, 5000) } }) } @SuppressLint("MissingPermission") private fun checkIfComeToMark() { fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? -> location?.let { if (::destinyMarker.isInitialized) { if (checkIfIsNear(it.latitude, destinyMarker.position.latitude) && checkIfIsNear(it.longitude, destinyMarker.position.longitude) ) { if (isFirstStop && !startButtonPressed) { startButtonPressed = true binding.buttonStart.visibility = View.VISIBLE binding.tvGoToStart.text = "Pulsa en comenzar y... Allá vamos!" } else if (!isFirstStop) { viewModel.getStoryFragment() /*destinyMarker.remove() viewModel.removeStop() viewModel.getStop()*/ } } } } } } private fun checkIfIsNear(myPosition: Double, destinyPosition: Double): Boolean { return myPosition > destinyPosition - 0.0002010551 && myPosition < destinyPosition + 0.0002010551 } private fun createNextStopMarker() { val coordinates = LatLng(nextStop.latitude, nextStop.longitude) val markerOptions = MarkerOptions().position(coordinates).title(nextStop.name) destinyMarker = map.addMarker(markerOptions)!! map.animateCamera( CameraUpdateFactory.newLatLngZoom(coordinates, 18.75f), 1, null ) randomSecondHappening = 0 secondsHappening = 0 } //RA-------------------------------------------------------------------------------------------- private val contractRA: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val data: Intent? = result.data destinyMarker.remove() viewModel.removeStop() viewModel.getStop() binding.tvTxtInGame.visibility = View.GONE viewModel.removeStoryFragment() } else { destinyMarker.remove() viewModel.removeStop() viewModel.getStop() binding.tvTxtInGame.visibility = View.GONE viewModel.removeStoryFragment() } } private fun launchExternalApk(packageName: String) { val intent = requireContext().packageManager.getLaunchIntentForPackage(packageName) intent?.let { contractRA.launch(it) } ?: run { // Manejar el caso en el que no se pueda lanzar la actividad Toast.makeText(requireContext(), "No se pudo iniciar la aplicación", Toast.LENGTH_SHORT) .show() } } private fun tryingApk() { val apkInputStream = resources.openRawResource(R.raw.apk_ra) val apkFile = File(requireContext().filesDir, "apk_ra") apkInputStream.copyTo(apkFile.outputStream()) val apkUri = FileProvider.getUriForFile( requireContext(), "com.example.arventurepath.ui.login_fragment.LoginFragment.FileProvider", apkFile ) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(apkUri, "application/vnd.android.package-archive") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } startActivity(intent) } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/in_game_fragment/InGameFragment.kt
682479289
package com.example.arventurepath.ui.list_arventure_fragment interface ArventureListListener { fun onArventureClick(idArventure: Int) }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/list_arventure_fragment/ArventureListListener.kt
1496172924
package com.example.arventurepath.ui.list_arventure_fragment.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.bumptech.glide.request.RequestOptions import com.example.arventurepath.R import com.example.arventurepath.data.models.ItemArventure import com.example.arventurepath.databinding.ItemViewpagerBinding import com.example.arventurepath.ui.list_arventure_fragment.ArventureListListener import java.util.Locale import kotlin.random.Random class ArventurePagerAdapter( private val context: Context, private val listener: ArventureListListener, private var arventures: MutableList<ItemArventure> = mutableListOf() ) : RecyclerView.Adapter<ArventurePagerAdapter.ViewHolder>() { inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = ItemViewpagerBinding.bind(view) fun setupListener(id: Int) { binding.root.setOnClickListener { listener.onArventureClick(id) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_viewpager, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder.binding) { tvTitle.text = arventures[position].title.uppercase(Locale.getDefault()) tvDistanceContent.text = arventures[position].distance.toString() tvTimeContent.text = arventures[position].time tvSummaryContent.text = arventures[position].summary } holder.setupListener(arventures[position].id) Glide.with(context) .load("http://abp-politecnics.com/2024/DAM01/filesToServer/imgStory/" + arventures[position].img) .error(R.drawable.aventura2) .apply(RequestOptions().centerCrop()) .into(holder.binding.imgArventure) } override fun getItemCount() = arventures.count() fun updateList(arventuresList: List<ItemArventure>) { arventures.clear() val listIndexes = mutableListOf<Int>() if (arventuresList.count() > 6) { for (i in 0 until 6) { var isArventureAdded : Boolean do { val randomIndex = Random.nextInt(0, arventuresList.size) if(!listIndexes.contains(randomIndex)){ listIndexes.add(randomIndex) arventures.add(arventuresList[randomIndex]) isArventureAdded = true }else{ isArventureAdded = false } } while (!isArventureAdded) } } else { for (arventure in arventuresList) { arventures.add(arventure) } } notifyDataSetChanged() } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/list_arventure_fragment/adapters/ArventurePagerAdapter.kt
1130738142
package com.example.arventurepath.ui.list_arventure_fragment.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.bumptech.glide.request.RequestOptions import com.example.arventurepath.R import com.example.arventurepath.data.models.ItemArventure import com.example.arventurepath.databinding.ItemRecyclerviewBinding import com.example.arventurepath.ui.list_arventure_fragment.ArventureListListener import java.util.Locale class ArventureListAdapter( private val context: Context, private val listener: ArventureListListener, private var arventures: MutableList<ItemArventure> = mutableListOf() ) : RecyclerView.Adapter<ArventureListAdapter.ViewHolder>() { inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = ItemRecyclerviewBinding.bind(view) fun setupListener(id: Int) { binding.root.setOnClickListener { listener.onArventureClick(id) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_recyclerview, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder.binding) { tvTitle.text = arventures[position].title.uppercase(Locale.getDefault()) } holder.setupListener(arventures[position].id) Glide.with(context) .load("http://abp-politecnics.com/2024/DAM01/filesToServer/imgStory/" + arventures[position].img) .error(R.drawable.aventura2) .apply(RequestOptions().centerCrop()) .into(holder.binding.imgArventure) } override fun getItemCount() = arventures.count() fun updateList(arventuresList: List<ItemArventure>) { arventures = arventuresList as MutableList<ItemArventure> notifyDataSetChanged() } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/list_arventure_fragment/adapters/ArventureListAdapter.kt
3642391298
package com.example.arventurepath.ui.list_arventure_fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import androidx.viewpager2.widget.ViewPager2 import com.example.arventurepath.R import com.example.arventurepath.databinding.FragmentListArventureBinding import com.example.arventurepath.ui.list_arventure_fragment.adapters.ArventureListAdapter import com.example.arventurepath.ui.list_arventure_fragment.adapters.ArventurePagerAdapter import com.google.android.material.tabs.TabLayoutMediator import kotlinx.coroutines.launch class ListArventureFragment : Fragment(), ArventureListListener { private lateinit var binding: FragmentListArventureBinding private lateinit var pagerAdapter: ArventurePagerAdapter private lateinit var listAdapter: ArventureListAdapter private val viewModel = ListArventureViewModel() private val args: ListArventureFragmentArgs by navArgs() private var isListScreen = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentListArventureBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupPagerAdapter() setupListAdapter() observeViewModel() viewModel.getListArventures() binding.btnGetList.setOnClickListener { if (!isListScreen) { binding.constraintRecycler.visibility = View.VISIBLE binding.viewPager.visibility = View.GONE binding.tabLayout.visibility = View.GONE binding.btnGetList.text = getString(R.string.back) } else { binding.constraintRecycler.visibility = View.GONE binding.viewPager.visibility = View.VISIBLE binding.tabLayout.visibility = View.VISIBLE binding.btnGetList.text = getString(R.string.seeMoreArventures) } isListScreen = !isListScreen } } private fun observeViewModel() { viewLifecycleOwner.lifecycleScope.launch { viewModel.listArventures.collect { arventuresList -> if (arventuresList.isNotEmpty()) { pagerAdapter.updateList(arventuresList) listAdapter.updateList(arventuresList) binding.constraintRecycler.visibility = View.GONE } } } viewLifecycleOwner.lifecycleScope.launch { viewModel.loading.collect { isLoading -> if (!isLoading) { binding.progressBar.visibility = View.GONE } } } } private fun setupPagerAdapter() { pagerAdapter = ArventurePagerAdapter(requireContext(), this) binding.viewPager.adapter = pagerAdapter setupCardsVisionConfig(binding.viewPager) TabLayoutMediator(binding.tabLayout, binding.viewPager) { _, _ -> }.attach() } private fun setupListAdapter() { listAdapter = ArventureListAdapter(requireContext(), this) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.layoutManager = LinearLayoutManager(requireContext()) binding.recyclerView.adapter = listAdapter } private fun setupCardsVisionConfig(viewPager: ViewPager2) { viewPager.offscreenPageLimit = 1 //Para que muestre las tarjetas laterales val nextItemVisiblePx = resources.getDimension(R.dimen.viewpager_next_item_visible) val currentItemHorizontalMarginPx = resources.getDimension(R.dimen.viewpager_current_item_horizontal_margin) val pageTranslationX = nextItemVisiblePx + currentItemHorizontalMarginPx val pageTransformer = ViewPager2.PageTransformer { page: View, position: Float -> page.translationX = -pageTranslationX * position // Next line scales the item's height. You can remove it if you don't want this effect page.scaleY = 1 - (0.25f * kotlin.math.abs(position)) // If you want a fading effect uncomment the next line: //page.alpha = 0.25f + (1 - abs(position)) } viewPager.setPageTransformer(pageTransformer) //Para que no se superpongan las vistas val itemDecoration = HorizontalMarginItemDecoration( requireContext(), R.dimen.viewpager_current_item_horizontal_margin ) viewPager.addItemDecoration(itemDecoration) } override fun onArventureClick(idArventure: Int) { findNavController().navigate( ListArventureFragmentDirections .actionListArventureFragment3ToDetailArventureFragment( idUser = args.idUser, idArventure = idArventure ) ) } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/list_arventure_fragment/ListArventureFragment.kt
2608470439
package com.example.arventurepath.ui.list_arventure_fragment import android.content.Context import android.graphics.Rect import android.view.View import androidx.annotation.DimenRes import androidx.recyclerview.widget.RecyclerView /** * Adds margin to the left and right sides of the RecyclerView item. * Adapted from https://stackoverflow.com/a/27664023/4034572 * @param horizontalMarginInDp the margin resource, in dp. */ class HorizontalMarginItemDecoration(context: Context, @DimenRes horizontalMarginInDp: Int) : RecyclerView.ItemDecoration() { private val horizontalMarginInPx: Int = context.resources.getDimension(horizontalMarginInDp).toInt() override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { outRect.right = horizontalMarginInPx outRect.left = horizontalMarginInPx } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/list_arventure_fragment/HorizontalMarginItemDecoration.kt
2721258815
package com.example.arventurepath.ui.list_arventure_fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.arventurepath.data.models.ItemArventure import com.example.arventurepath.data.remote.DataProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class ListArventureViewModel : ViewModel() { private val _listArventures = MutableStateFlow<List<ItemArventure>>(listOf()) val listArventures: StateFlow<List<ItemArventure>> = _listArventures private val _loading = MutableStateFlow(true) val loading: StateFlow<Boolean> = _loading fun getListArventures() { viewModelScope.launch(Dispatchers.IO) { val deferred = async { _listArventures.emit(DataProvider.getListArventures()) } deferred.await() _loading.emit(false) } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/list_arventure_fragment/ListArventureViewModel.kt
1631040985
package com.example.arventurepath.ui.score_fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.arventurepath.data.models.ArventureFinal import com.example.arventurepath.data.remote.DataProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class ScoreFragmentViewModel : ViewModel() { private val _arventureFinal = MutableStateFlow(ArventureFinal()) val arventureFinal: StateFlow<ArventureFinal> = _arventureFinal private val _loading = MutableStateFlow(true) val loading: StateFlow<Boolean> = _loading fun getArventureScore(idArventure: Int){ viewModelScope.launch(Dispatchers.IO) { val deferred = async { val response = DataProvider.getArventureScore(idArventure) _arventureFinal.emit(response) } deferred.await() _loading.emit(false) } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/score_fragment/ScoreFragmentViewModel.kt
343840451
package com.example.arventurepath.ui.score_fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.arventurepath.R import com.example.arventurepath.data.models.Stop import com.example.arventurepath.databinding.FragmentScoreBinding import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import kotlinx.coroutines.launch import java.sql.Time class ScoreFragment : Fragment(), OnMapReadyCallback { private lateinit var binding: FragmentScoreBinding private lateinit var map: GoogleMap private val args: ScoreFragmentArgs by navArgs() private val viewModel = ScoreFragmentViewModel() private var stops = listOf<Stop>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentScoreBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) createFragment() observedViewModel() viewModel.getArventureScore(args.idArventure) binding.buttonAccept.setOnClickListener { findNavController().navigate( ScoreFragmentDirections.actionScoreFragment2ToListArventureFragment( idUser = args.idUser ) ) } } private fun observedViewModel() { viewLifecycleOwner.lifecycleScope.launch { viewModel.arventureFinal.collect { binding.arventureTitle.text = it.name.uppercase() binding.distanceArventure.text = it.distance binding.estimateTimeArventure.text = it.estimateTime binding.stepsArventure.text = args.steps.toString() binding.timeArventure.text = getFormattedTime(args.totalSeconds) //binding.timeArventure.text = args.totalSeconds.toString() binding.storyNameArventure.text = it.storyName stops = it.stops setAchievements() Glide.with(requireContext()) .load("http://abp-politecnics.com/2024/DAM01/filesToServer/imgStory/" + it.img) .error(R.drawable.aventura2) .apply(RequestOptions().centerCrop()) .into(binding.imgArventure) } } viewLifecycleOwner.lifecycleScope.launch { viewModel.loading.collect { isLoading -> if (!isLoading) { binding.progressBar.visibility = View.GONE binding.linearTitle.visibility = View.VISIBLE binding.linearImg.visibility = View.VISIBLE binding.linearMap.visibility = View.VISIBLE binding.linearAchievement.visibility = View.VISIBLE createFragment() } } } } private fun setAchievements() { val marginInPixels = resources.getDimensionPixelOffset(R.dimen.smallMargin) val marginLayoutParams = ViewGroup.MarginLayoutParams( resources.getDimensionPixelOffset(R.dimen.achievementWidth), resources.getDimensionPixelOffset(R.dimen.achievementHeight) ) marginLayoutParams.setMargins( marginInPixels, marginInPixels, marginInPixels, marginInPixels ) Log.i(">", "TAMAÑO DE LA LISTA ->" + args.achievements.achievements.count()) Log.i(">", "ENTRA EN EL BUCLE") binding.linearImgAchievement.removeAllViews() args.achievements.achievements.forEach { achievement -> Log.i(">", "DA UNA VUELTA") Log.i(">", "NOMBRE DEL LOGRO -> " + achievement.name) val imageView = ImageView(context).apply { layoutParams = marginLayoutParams Glide.with(requireContext()) .load("http://abp-politecnics.com/2024/DAM01/filesToServer/imgAchievement/" + achievement.img) .error(R.drawable.aventura2) .apply(RequestOptions().centerCrop()) .into(this) } binding.linearImgAchievement.addView(imageView) } } private fun createFragment() { binding.frgmntMap.getFragment<SupportMapFragment>().getMapAsync(this) } override fun onMapReady(googleMap: GoogleMap) { map = googleMap createMarker() } private fun createMarker() { for (stop in stops){ val coordinates = LatLng(stop.latitude, stop.longitude) val marker : MarkerOptions = MarkerOptions().position(coordinates).title(stop.name) map.addMarker(marker) map.animateCamera( CameraUpdateFactory.newLatLngZoom(coordinates, 11.8f),4000, null ) } } private fun getFormattedTime(timeInSeconds: Int): String { val hours = timeInSeconds / 3600 val minutes = (timeInSeconds % 3600) / 60 val seconds = timeInSeconds % 60 val timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds) //binding.timeArventure.text = timeString return timeString } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/ui/score_fragment/ScoreFragment.kt
1546558587
package com.example.arventurepath.utils import android.annotation.SuppressLint import android.content.Context import android.location.Location import android.location.LocationManager import com.google.android.gms.location.LocationServices import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine @OptIn(ExperimentalCoroutinesApi::class) class MyLocationServices { @SuppressLint("MissingPermission") suspend fun getUserLocation(context: Context): Location? { val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context) val isUserLocationPermissionGranted = true val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager val isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) if (!isGPSEnabled || !isUserLocationPermissionGranted) { return null } return suspendCancellableCoroutine { cont -> fusedLocationProviderClient.lastLocation.apply { if (isComplete) { if (isSuccessful) { cont.resume(result) {} } else { cont.resume(null) {} } return@suspendCancellableCoroutine } addOnSuccessListener { cont.resume(it) {} } addOnFailureListener { cont.resume(null) {} } addOnCanceledListener { cont.resume(null) {} } } } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/utils/MyLocationServices.kt
4066836919
package com.example.arventurepath.utils object Constants { const val BASE_URL = "http://abp-politecnics.com/2024/dam01/api/" const val FENIX_PACKAGE = "com.unity.fenix" const val DRAGON_PACKAGE = "com.unity.template.dragon" const val ROBOT_PACKAGE = "com.unity.template.ar_robot" const val RETROFIT_TIMEOUT_IN_SECOND: Long = 30 const val REQUEST_PERMISSION = 666 const val fitnessPermissionsRequestCode = 1 }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/utils/Constants.kt
420426793
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class UserToPlay( val id: Int = 0, var name: String = "", val mail: String = "", val passwd: String = "", val img: String = "", val distance: Double = 0.0, val steps: Int = 0, val achievement: MutableList<Achievement> = mutableListOf() ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/UserToPlay.kt
2472769598
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class UserToRegister( val id: Int = 0, val name: String = "", val mail: String = "", val passwd: String = "", val img: String = "", val distance: Double = 0.0, val steps: Int = 0 ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/UserToRegister.kt
1820132603
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class ArventureToPlay( val id: Int = 0, val name: String = "", val route: Route = Route(), val story: Story = Story(), val achievement: Achievement = Achievement(), val happenings: List<Happening> = listOf() ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/ArventureToPlay.kt
2853203942
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class ArventureFinal( val id: Int = 0, val name: String = "", val estimateTime: String = "", val distance: String = "", val img: String = "", var steps: Int = 0, var time: String = "", val storyName: String = "", val stops: List<Stop> = listOf(), var achievements: MutableList<Achievement> = mutableListOf() ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/ArventureFinal.kt
247872511
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class StoryFragment( val id: Int = 0, val ordinal: Int = 0, val content: String = "" ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/StoryFragment.kt
575912623
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class ItemArventure( val id: Int = -1, val title: String = "", val summary: String = "", val time: String = "", val distance: String = "", val img: String = "" ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/ItemArventure.kt
3075605559
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class ArventureDetail( val id: Int = 0, val name: String = "", val time: String = "", val distance: String = "", val img: String = "", val summary: String = "", val origin: String = "", val nameStory: String = "", val latitude: Double = 0.0, val longitude: Double = 0.0 ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/ArventureDetail.kt
1318664610
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class ListAchievements( val achievements: MutableList<Achievement> ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/ListAchievements.kt
1771497685
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Story( var id: Int = 0, var name: String = "", var summary: String = "", var img: String = "", var storyFragments: List<StoryFragment> = listOf(), ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/Story.kt
4002409604
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Happening( val id: Int = 0, val name: String = "", val text: String = "", val type: String = "", val img: String = "", ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/Happening.kt
4205879107
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Achievement( val id: Int = 0, val name: String = "", val img: String = "" ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/Achievement.kt
1185696610
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Route( val id: Int = 0, val name: String = "", val time: String = "", val steps: Int = 0, val distance: Double = 0.0, val stops: List<Stop> = listOf(), ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/Route.kt
48193707
package com.example.arventurepath.data.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Stop( val id: Int = 0, val name: String = "", var longitude: Double = 0.0, var latitude: Double = 0.0, ) : Parcelable
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/models/Stop.kt
2045205795
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class RouteResponse( @SerializedName("arventure") var arventure: ArrayList<ArventuresResponse>?, @SerializedName("stop") var stop: ArrayList<StopResponse>?, @SerializedName("id") var id: Int?, @SerializedName("time") var time: String?, @SerializedName("steps") var steps: Int?, @SerializedName("distance") var distance: Double?, @SerializedName("name") var name: String? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/RouteResponse.kt
693136985
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class FragmentResponse( @SerializedName("id") var id: Int?, @SerializedName("ordinal") var ordinal: Int?, @SerializedName("idStory") var idStory: Int?, @SerializedName("content") var content: String? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/FragmentResponse.kt
1345185827
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class UserResponse( @SerializedName("id") var id: Int?, @SerializedName("name") var name: String?, @SerializedName("mail") var mail: String?, @SerializedName("passwd") var passwd: String?, @SerializedName("img") var img: String?, @SerializedName("distance") var distance: Double?, @SerializedName("steps") var steps: Int?, @SerializedName("achievement") var achievement: ArrayList<AchievementResponse>?, @SerializedName("arventure") var arventure: ArrayList<ArventuresResponse>? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/UserResponse.kt
285721542
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class StopResponse( @SerializedName("id") var id: Int?, @SerializedName("name") var name: String?, @SerializedName("longitude") var longitude: Double?, @SerializedName("latitude") var latitude: Double?, @SerializedName("idRoute") var idRoute: Int? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/StopResponse.kt
1887720387
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class StoryResponse( @SerializedName("arventure") var arventure: ArrayList<ArventuresResponse>?, @SerializedName("fragment") var fragment: ArrayList<FragmentResponse>?, @SerializedName("happening") var happening: ArrayList<HappeningResponse>?, @SerializedName("id") var id: Int?, @SerializedName("name") var name: String?, @SerializedName("img") var img: String?, @SerializedName("summary") var summary: String? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/StoryResponse.kt
2102082910
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class HappeningResponse( @SerializedName("id") var id: Int?, @SerializedName("name") var name: String?, @SerializedName("text") var text: String?, @SerializedName("type") var type: String?, @SerializedName("url") var url: String?, @SerializedName("idStory") var idStory: Int?, @SerializedName("arventure") var arventure: ArrayList<ArventuresResponse>? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/HappeningResponse.kt
22127609
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class AchievementResponse( @SerializedName("id") var id: Int?, @SerializedName("name") var name: String?, @SerializedName("img") var img: String?, @SerializedName("arventure") var arventure: ArrayList<ArventuresResponse>?, @SerializedName("user") var user: ArrayList<UserResponse>? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/AchievementResponse.kt
86096172
package com.example.arventurepath.data.remote.responses import com.google.gson.annotations.SerializedName data class ArventuresResponse( @SerializedName("achievement") var achievement: AchievementResponse?, @SerializedName("route") var routeResponse: RouteResponse?, @SerializedName("story") var storyResponse: StoryResponse?, @SerializedName("happening") var happening: ArrayList<HappeningResponse>?, @SerializedName("user") var user: ArrayList<UserResponse>?, @SerializedName("id") var id: Int?, @SerializedName("name") var name: String?, @SerializedName("idRoute") var idRoute: Int?, @SerializedName("idStory") var idStory: Int?, @SerializedName("idAchievement") var idAchievement: Int? )
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/responses/ArventuresResponse.kt
1350896881
package com.example.arventurepath.data.remote.retrofit import com.example.arventurepath.utils.Constants.BASE_URL import com.google.gson.GsonBuilder import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.Executors object RetrofitClient { private val retrofit: Retrofit private val remoteApiService: RemoteApiService init { val gson = GsonBuilder().setLenient().create() retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .callbackExecutor(Executors.newSingleThreadExecutor()) .build() remoteApiService = retrofit.create(RemoteApiService::class.java) } fun getApiServices(): RemoteApiService { return remoteApiService } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/retrofit/RetrofitClient.kt
574552751
package com.example.arventurepath.data.remote.retrofit import android.util.Log import com.example.arventurepath.data.models.UserToPlay import com.example.arventurepath.data.models.UserToRegister import com.example.arventurepath.data.remote.responses.AchievementResponse import com.example.arventurepath.data.remote.responses.ArventuresResponse import com.example.arventurepath.data.remote.responses.UserResponse import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path interface RemoteApiService { @GET("arventures") suspend fun getListArventures(): Response<List<ArventuresResponse>> @GET("arventures/{idArventure}") suspend fun getArventureById( @Path("idArventure") idArventure: Int ): Response<ArventuresResponse> @GET("achievements") suspend fun getListAchievements( ): Response<List<AchievementResponse>> @GET("users") suspend fun getListUsers( ): Response<List<UserResponse>> @GET("users/{idUser}") suspend fun getUserById( @Path("idUser") idUser: Int ): Response<UserResponse> @POST("users") suspend fun registerUser( @Body userToRegister: UserToRegister ): Response<UserResponse> @POST("users/update/{id}") suspend fun updateUser( @Path("id") id: Int, @Body userToPlay: UserToPlay ): Response<Unit> }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/retrofit/RemoteApiService.kt
3327711674
package com.example.arventurepath.data.remote import android.util.Log import com.example.arventurepath.data.models.Achievement import com.example.arventurepath.data.models.ArventureDetail import com.example.arventurepath.data.models.ArventureFinal import com.example.arventurepath.data.models.ArventureToPlay import com.example.arventurepath.data.models.Happening import com.example.arventurepath.data.models.ItemArventure import com.example.arventurepath.data.models.Route import com.example.arventurepath.data.models.Stop import com.example.arventurepath.data.models.Story import com.example.arventurepath.data.models.StoryFragment import com.example.arventurepath.data.models.UserToPlay import com.example.arventurepath.data.models.UserToRegister import com.example.arventurepath.data.remote.responses.AchievementResponse import com.example.arventurepath.data.remote.responses.HappeningResponse import com.example.arventurepath.data.remote.responses.RouteResponse import com.example.arventurepath.data.remote.responses.StoryResponse import com.example.arventurepath.data.remote.retrofit.RetrofitClient object DataProvider { private val remoteApiService = RetrofitClient.getApiServices() suspend fun getListArventures(): List<ItemArventure> { val arventuresListResponse = remoteApiService.getListArventures().body()!! val arventuresList = mutableListOf<ItemArventure>() arventuresListResponse.forEach { arventureResponse -> arventuresList.add( ItemArventure( arventureResponse.id ?: -1, arventureResponse.name ?: "", arventureResponse.storyResponse?.summary ?: "", transformTime(arventureResponse.routeResponse?.time ?: ""), transformDistance(arventureResponse.routeResponse?.distance ?: 0.0), arventureResponse.storyResponse?.img ?: "" ) ) } return arventuresList } suspend fun getListUsers(): List<UserToRegister>{ val usersListResponse = remoteApiService.getListUsers().body()!! val usersList = mutableListOf<UserToRegister>() usersListResponse.forEach {userResponse -> usersList.add( UserToRegister( userResponse.id ?: 0, userResponse.name ?: "", userResponse.mail ?: "", userResponse.passwd ?: "", userResponse.img ?: "", userResponse.distance ?: 0.0, userResponse.steps ?: -1 ) ) } return usersList } suspend fun getListAchievements(): List<Achievement> { val achievements = mutableListOf<Achievement>() val achievementsResponse = remoteApiService.getListAchievements().body()!! if (!achievementsResponse.isNullOrEmpty()) { achievementsResponse.forEach { if (it.arventure.isNullOrEmpty()) { achievements.add( Achievement( it.id ?: 0, it.name ?: "", it.img ?: "" ) ) } } achievements.removeAll { it.name.contains("Completa la aventura:") } achievements.forEach { Log.i(">", it.name) } } return achievements } suspend fun getArventureDetail(idArventure: Int): ArventureDetail { val arventureResponse = remoteApiService.getArventureById(idArventure).body()!! return ArventureDetail( arventureResponse.id ?: 0, arventureResponse.name ?: "", transformTime(arventureResponse.routeResponse?.time ?: ""), transformDistance(arventureResponse.routeResponse?.distance ?: 0.0), arventureResponse.storyResponse?.img ?: "", arventureResponse.storyResponse?.summary ?: "", arventureResponse.routeResponse?.stop?.get(0)?.name ?: "", arventureResponse.storyResponse?.name ?: "", arventureResponse.routeResponse?.stop?.get(0)?.latitude ?: 0.0, arventureResponse.routeResponse?.stop?.get(0)?.longitude ?: 0.0, ) } suspend fun getArventureScore(idArventure: Int): ArventureFinal { val arventuresResponse = remoteApiService.getArventureById(idArventure).body()!! val route = takeRouteFromArventureResponse(arventuresResponse.routeResponse) val achievement = takeAchievementFromArventureResponse(arventuresResponse.achievement) return ArventureFinal( arventuresResponse.id ?: 0, arventuresResponse.name ?: "", transformTime(arventuresResponse.routeResponse?.time ?: ""), transformDistance(arventuresResponse.routeResponse?.distance ?: 0.0), arventuresResponse.storyResponse?.img ?: "", 0, "", arventuresResponse.storyResponse?.name ?: "", route.stops, mutableListOf(achievement) ) } private fun transformDistance(distanceToTransform: Double): String { return String.format("%.2f", distanceToTransform) + " km" } private fun transformTime(timeToTransform: String): String { return timeToTransform.substring(0, 2) + "h " + timeToTransform.substring(3, 5) + "min" } suspend fun registerUser(userToRegister: UserToRegister): UserToPlay { val userResponse = remoteApiService.registerUser(userToRegister).body()!! val achievements = mutableListOf<Achievement>() if (!userResponse.achievement.isNullOrEmpty()) { userResponse.achievement!!.forEach { achievements.add( Achievement( it.id ?: 0, it.name ?: "", it.img ?: "" ) ) } } return UserToPlay( userResponse.id ?: 0, userResponse.name ?: "", userResponse.mail ?: "", userResponse.passwd ?: "", userResponse.img ?: "", userResponse.distance ?: 0.0, userResponse.steps ?: 0, achievements ) } suspend fun getUserById(idUser: Int): UserToPlay { val userResponse = remoteApiService.getUserById(idUser).body()!! val achievements = mutableListOf<Achievement>() if (!userResponse.achievement.isNullOrEmpty()) { userResponse.achievement!!.forEach { achievements.add( Achievement( it.id ?: 0, it.name ?: "", it.img ?: "", ) ) } } return UserToPlay( userResponse.id ?: 0, userResponse.name ?: "", userResponse.mail ?: "", userResponse.passwd ?: "", userResponse.img ?: "", userResponse.distance ?: 0.0, userResponse.steps ?: 0, achievements ) } suspend fun updateUser(idUser: Int, user: UserToPlay){ remoteApiService.updateUser(idUser, user) } suspend fun getArventureToPlay(idArventure: Int): ArventureToPlay { val arventureResponse = remoteApiService.getArventureById(idArventure).body()!! val route = takeRouteFromArventureResponse(arventureResponse.routeResponse) val story = takeStoryFromArventureResponse(arventureResponse.storyResponse) val achievement = takeAchievementFromArventureResponse(arventureResponse.achievement) val happenings = takeHappeningsFromArventureResponse(arventureResponse.happening) return ArventureToPlay( arventureResponse.id ?: 0, arventureResponse.name ?: "", route, story, achievement, happenings ) } private fun takeHappeningsFromArventureResponse(happeningsResponse: ArrayList<HappeningResponse>?): List<Happening> { val happenings = mutableListOf<Happening>() if (!happeningsResponse.isNullOrEmpty()) { happeningsResponse.forEach { happenings.add( Happening( it.id ?: 0, it.name ?: "", it.text ?: "", it.type ?: "", it.url ?: "", ) ) } } return happenings } private fun takeAchievementFromArventureResponse(achievementResponse: AchievementResponse?): Achievement { return if (achievementResponse != null) { Achievement( achievementResponse.id ?: 0, achievementResponse.name ?: "", achievementResponse.img ?: "" ) } else { Achievement() } } private fun takeStoryFromArventureResponse(storyResponse: StoryResponse?): Story { val storyFragments = mutableListOf<StoryFragment>() if (!storyResponse?.fragment.isNullOrEmpty()) { storyResponse?.fragment?.forEach { storyFragments.add( StoryFragment( it.id ?: 0, it.ordinal ?: 0, it.content ?: "" ) ) } } return if (storyResponse != null) { Story( storyResponse.id ?: 0, storyResponse.name ?: "", storyResponse.summary ?: "", storyResponse.img ?: "", storyFragments ) } else { Story() } } private fun takeRouteFromArventureResponse(routeResponse: RouteResponse?): Route { val stops = mutableListOf<Stop>() if (!routeResponse?.stop.isNullOrEmpty()) { routeResponse?.stop?.forEach { stops.add( Stop( it.id ?: 0, it.name ?: "", it.longitude ?: 0.0, it.latitude ?: 0.0 ) ) } } return if (routeResponse != null) { Route( routeResponse.id ?: 0, routeResponse.name ?: "", routeResponse.time ?: "", routeResponse.steps ?: 0, routeResponse.distance ?: 0.0, stops ) } else { Route() } } }
ARventurePathAndroid/app/src/main/java/com/example/arventurepath/data/remote/DataProvider.kt
628046281
package com.google.mediapipe.examples.poselandmarker 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.google.mediapipe.examples.poselandmarker", appContext.packageName) } }
dragonhack2024/androidApp/android/app/src/androidTest/java/com/google/mediapipe/examples/poselandmarker/ExampleInstrumentedTest.kt
918805731
package com.google.mediapipe.examples.poselandmarker 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) } }
dragonhack2024/androidApp/android/app/src/test/java/com/google/mediapipe/examples/poselandmarker/ExampleUnitTest.kt
2434517470
/* * Copyright 2023 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mediapipe.examples.poselandmarker import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.mediapipe.examples.poselandmarker.api.FitRepository import com.google.mediapipe.tasks.vision.poselandmarker.PoseLandmarkerResult import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import java.util.concurrent.Flow import javax.inject.Inject import kotlin.math.acos import kotlin.math.sqrt /** * This ViewModel is used to store pose landmarker helper settings */ @HiltViewModel class MainViewModel @Inject constructor( private val fitRepository: FitRepository ) : ViewModel() { val stateFlowOfColors = MutableLiveData<Boolean>(false) private var _model = PoseLandmarkerHelper.MODEL_POSE_LANDMARKER_FULL private var _delegate: Int = PoseLandmarkerHelper.DELEGATE_CPU private var _minPoseDetectionConfidence: Float = PoseLandmarkerHelper.DEFAULT_POSE_DETECTION_CONFIDENCE private var _minPoseTrackingConfidence: Float = PoseLandmarkerHelper .DEFAULT_POSE_TRACKING_CONFIDENCE private var _minPosePresenceConfidence: Float = PoseLandmarkerHelper .DEFAULT_POSE_PRESENCE_CONFIDENCE val currentDelegate: Int get() = _delegate val currentModel: Int get() = _model val currentMinPoseDetectionConfidence: Float get() = _minPoseDetectionConfidence val currentMinPoseTrackingConfidence: Float get() = _minPoseTrackingConfidence val currentMinPosePresenceConfidence: Float get() = _minPosePresenceConfidence fun setDelegate(delegate: Int) { _delegate = delegate } fun setMinPoseDetectionConfidence(confidence: Float) { _minPoseDetectionConfidence = confidence } fun setMinPoseTrackingConfidence(confidence: Float) { _minPoseTrackingConfidence = confidence } fun setMinPosePresenceConfidence(confidence: Float) { _minPosePresenceConfidence = confidence } fun setModel(model: Int) { _model = model } var isUp: Boolean = false var isFirstDetected: Boolean = false var counter: Float = 0f var userId = 0 var challengeId = "" fun sendData() { viewModelScope.launch { fitRepository.putExerciseToChallenge(userId, challengeId, "1", counter.toInt()) } } fun calculateAngleBetweenArms( poseLandmarkerResults: PoseLandmarkerResult, imageHeight: Int, imageWidth: Int, ) { poseLandmarkerResults.let { poseLandmarkerResult -> if (poseLandmarkerResults.landmarks().isEmpty() || poseLandmarkerResults.landmarks() .get(0).isEmpty() ) { return } val leftShoulder = poseLandmarkerResults.landmarks().get(0).get(11) val leftElbow = poseLandmarkerResults.landmarks().get(0).get(13) val leftWrist = poseLandmarkerResults.landmarks().get(0).get(15) val vectorFirst = Pair(leftElbow.x() - leftShoulder.x(), leftElbow.y() - leftShoulder.y()) val vectorSecond = Pair(leftElbow.x() - leftWrist.x(), leftElbow.y() - leftWrist.y()) //calculate angle between arms val dotProduct = vectorFirst.first * vectorSecond.first + vectorFirst.second * vectorSecond.second val sizeFirst = sqrt((vectorFirst.first * vectorFirst.first + vectorFirst.second * vectorFirst.second).toDouble()) val sizeSecond = sqrt((vectorSecond.first * vectorSecond.first + vectorSecond.second * vectorSecond.second).toDouble()) val cos = dotProduct / (sizeFirst * sizeSecond) val angle = Math.toDegrees(acos(cos)) println("angle: $angle, counter: $counter") if (angle > 120) { //arms are up if (isFirstDetected) { isUp = true isFirstDetected = false } else if (!isUp) { isUp = true counter += 0.5f stateFlowOfColors.postValue(true) } } else if (angle < 90) { if (isFirstDetected) { isUp = false isFirstDetected = false } else if (isUp) { isUp = false counter += 0.5f //play beep sound stateFlowOfColors.postValue(false) } } } } }
dragonhack2024/androidApp/android/app/src/main/java/com/google/mediapipe/examples/poselandmarker/MainViewModel.kt
4198492530
/* * Copyright 2023 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mediapipe.examples.poselandmarker import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.google.mediapipe.examples.poselandmarker.compose.ComposeMainActivity import com.google.mediapipe.examples.poselandmarker.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var activityMainBinding: ActivityMainBinding private val viewModel : MainViewModel by viewModels() //register listeer for stateFlowOfColors in viewmodel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //getIntent extras val extras = intent.extras val challengeId = extras?.getString("challengeId") val userId = extras?.getInt("userId") viewModel.userId = userId ?: 0 viewModel.challengeId = challengeId ?: "" activityMainBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(activityMainBinding.root) //find @+id/button_send_data and setOnClickListener activityMainBinding.buttonSendData.setOnClickListener { viewModel.sendData() val intent = Intent(this, ComposeMainActivity::class.java) startActivity(intent) } val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragment_container) as NavHostFragment //set background to fragment_container navHostFragment.view?.setBackgroundColor(resources.getColor(R.color.mp_color_secondary)) viewModel.stateFlowOfColors.observe(this, Observer { if (!it) { activityMainBinding.navigation.setBackgroundColor(resources.getColor(R.color.mp_color_error)) //setcolor of navbar } else { activityMainBinding.navigation.setBackgroundColor(resources.getColor(R.color.mp_color_secondary)) } //find @+id/textView activityMainBinding.textView.text = "${viewModel.counter.toInt()}" }) val navController = navHostFragment.navController activityMainBinding.navigation.setupWithNavController(navController) activityMainBinding.navigation.setOnNavigationItemReselectedListener { // ignore the reselection } } override fun onBackPressed() { finish() } }
dragonhack2024/androidApp/android/app/src/main/java/com/google/mediapipe/examples/poselandmarker/MainActivity.kt
2241730624
package com.google.mediapipe.examples.poselandmarker.di import com.google.mediapipe.examples.poselandmarker.api.ApiService import com.google.mediapipe.examples.poselandmarker.api.FitRepository import com.google.mediapipe.examples.poselandmarker.core.Constants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class AppModule { @Provides @Singleton fun provideApiService(): ApiService { val loggingInterceptor = HttpLoggingInterceptor() val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() return Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(Constants.BASE_URL) .client(okHttpClient) .build() .create(ApiService::class.java) } @Provides @Singleton fun fitRepository(apiService: ApiService): FitRepository { return FitRepository(apiService) } }
dragonhack2024/androidApp/android/app/src/main/java/com/google/mediapipe/examples/poselandmarker/di/AppModule.kt
318791466
package com.google.mediapipe.examples.poselandmarker.core import android.content.Context class PreferencesManager(context : Context) { companion object { const val INSTALL_ID = "install_id" const val USERNAME = "username" } private val sharedPreferences = context.getSharedPreferences("Sweatify22222", Context.MODE_PRIVATE) fun saveString(key: String, value: String) { sharedPreferences.edit().putString(key, value).apply() } fun getString(key: String): String? { return sharedPreferences.getString(key, null) } fun saveInt(key: String, value: Int) { sharedPreferences.edit().putInt(key, value).apply() } fun getInt(key: String): Int { return sharedPreferences.getInt(key, 0) } }
dragonhack2024/androidApp/android/app/src/main/java/com/google/mediapipe/examples/poselandmarker/core/PreferencesManager.kt
2450372857
package com.google.mediapipe.examples.poselandmarker.core import java.time.LocalDateTime fun formatDateToString(date: LocalDateTime): String { val year = date.year val month = date.monthValue val day = date.dayOfMonth val hour = date.hour val minute = date.minute // Format: 31/12/2021 23:59 return "${String.format("%02d", day)}/${String.format("%02d", month)}/$year $hour:$minute" }
dragonhack2024/androidApp/android/app/src/main/java/com/google/mediapipe/examples/poselandmarker/core/HelperFunctions.kt
1297347629
package com.google.mediapipe.examples.poselandmarker.core object Constants { const val BASE_URL = "http://192.168.72.146:3000/" }
dragonhack2024/androidApp/android/app/src/main/java/com/google/mediapipe/examples/poselandmarker/core/Constants.kt
978989876
package com.google.mediapipe.examples.poselandmarker.compose import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Button import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.google.mediapipe.examples.poselandmarker.MainActivity import com.google.mediapipe.examples.poselandmarker.compose.ui.features.home.HomeScreen import com.google.mediapipe.examples.poselandmarker.compose.ui.features.login.RandomGenerateIdLogin import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ComposeMainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val context = LocalContext.current val navController = rememberNavController() Surface( modifier = Modifier.fillMaxSize(), ) { NavHost( navController = navController, startDestination = "login" ) { composable("login") { RandomGenerateIdLogin(navController = navController) } composable("home") { HomeScreen( navController = navController ) } } } } } } @Composable fun ButtonTest() { val context = LocalContext.current Button(onClick = { //open the .MainActivity val intent = Intent(context, MainActivity::class.java) context.startActivity(intent) }) { } }
dragonhack2024/androidApp/android/app/src/main/java/com/google/mediapipe/examples/poselandmarker/compose/ComposeMainActivity.kt
3644498850