content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.teste_tabs.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
class ViewPagerAdapter(
fragmentActivity: FragmentActivity
) : FragmentStateAdapter(fragmentActivity) {
private val fragmentList: MutableList<Fragment> = ArrayList()
private val titleList: MutableList<Int> = ArrayList()
fun getTitle(pos: Int): Int = titleList[pos]
fun addFragment(fragment: Fragment, title: Int) {
fragmentList.add(fragment)
titleList.add(title)
}
override fun getItemCount(): Int = fragmentList.size
override fun createFragment(position: Int): Fragment = fragmentList[position]
} | teste-tabs/app/src/main/java/com/example/teste_tabs/adapter/ViewPagerAdapter.kt | 1938819273 |
package com.nelson.le
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.nelson.le", appContext.packageName)
}
} | nelsonhongle_comp304lab3_ex2/app/src/androidTest/java/com/nelson/le/ExampleInstrumentedTest.kt | 2787861334 |
package com.nelson.le
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)
}
} | nelsonhongle_comp304lab3_ex2/app/src/test/java/com/nelson/le/ExampleUnitTest.kt | 2997373683 |
package com.nelson.le.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/ui/theme/Color.kt | 3146030867 |
package com.nelson.le.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun Nelsonhongle_comp304lab3_ex2Theme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/ui/theme/Theme.kt | 334093050 |
package com.nelson.le.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/ui/theme/Type.kt | 3675965621 |
package com.nelson.le
import android.os.Bundle
import android.view.animation.AnimationSet
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sunImageView: ImageView = findViewById(R.id.sunImageView)
val earthImageView: ImageView = findViewById(R.id.earthImageView)
val sunAnimationSet = AnimationSet(true)
val sunRotateAnimation = AnimationUtils.loadAnimation(this, R.anim.rotate_animation)
val sunScaleAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_animation)
sunAnimationSet.addAnimation(sunRotateAnimation)
sunAnimationSet.addAnimation(sunScaleAnimation)
sunImageView.startAnimation(sunAnimationSet)
earthImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate_animation))
}
}
| nelsonhongle_comp304lab3_ex2/app/src/main/java/com/nelson/le/MainActivity.kt | 175347711 |
package com.example.practice_musicplayer
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.practice_musicplayer", appContext.packageName)
}
} | practice_musicPlayer/app/src/androidTest/java/com/example/practice_musicplayer/ExampleInstrumentedTest.kt | 781696026 |
package com.example.practice_musicplayer
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)
}
} | practice_musicPlayer/app/src/test/java/com/example/practice_musicplayer/ExampleUnitTest.kt | 1314916932 |
package com.example.practice_musicplayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.bumptech.glide.request.transition.Transition.ViewAdapter
import com.example.practice_musicplayer.adapters.AdapterViewPager
import com.example.practice_musicplayer.adapters.MusicAdapter
import com.example.practice_musicplayer.databinding.ActivityViewPagerBinding
import com.example.practice_musicplayer.utils.DpData
import com.example.practice_musicplayer.utils.RetrofitService
import com.example.practice_musicplayer.utils.ViewPagerExtensions.addCarouselEffect
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.ArrayList
class ViewPager : AppCompatActivity() {
private val binding by lazy { ActivityViewPagerBinding.inflate(layoutInflater) }
lateinit var viewPagerAdapter: AdapterViewPager
private val apiService = RetrofitService.getInstance()
private var songList: ArrayList<MusicClass>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
getNewSongs()
}
private fun initViewPager() {
// binding.viewPager.addCarouselEffect()
// binding.viewPager.adapter = adapter
// adapter.submitList(dpData.dummyData)
}
private fun getNewSongs() {
val apiService =
apiService.getNewSongs(
)
apiService?.enqueue(object : Callback<String?> {
override fun onResponse(call: Call<String?>, response: Response<String?>) {
if (response.isSuccessful) {
if (response.body() != null) {
val jsonresponse: String = response.body().toString()
// on below line we are initializing our adapter.
Log.d("response", jsonresponse)
recycleNewSongs(jsonresponse)
} else {
Log.i(
"onEmptyResponse",
"Returned empty response"
)
}
}
}
override fun onFailure(call: Call<String?>, t: Throwable) {
Log.e(
"ERROR",
t.message.toString()
)
}
})
}
private fun recycleNewSongs(response: String) = try {
val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList()
val obj = JSONObject(response)
val dataArray = obj.getJSONArray("data")
// Log.d("RESPONSE", dataArray.toString())
for (i in 0 until dataArray.length()) {
val dataObject = dataArray.getJSONObject(i)
val musicItem = MusicClass(
id = dataObject.getInt("id"),
date = dataObject.getString("date"),
name = dataObject.getString("name"),
duration = dataObject.getString("duration"),
artist = dataObject.getString("artist"),
coverArtUrl = dataObject.getString("cover_art_url"),
url = dataObject.getString("url")
)
modelRecyclerArrayList.add(musicItem)
}
// Log.d("RESPONSE", modelRecyclerArrayList.toString())
songList = modelRecyclerArrayList
// newSongRecycleData(songList!!)
} catch (e: JSONException) {
e.printStackTrace()
}
// private fun newSongRecycleData(array: ArrayList<MusicClass>) {
//
// binding.viewPager.addCarouselEffect()
// viewPagerAdapter = AdapterViewPager(this,binding.viewPager, array, )
// binding.viewPager.adapter = viewPagerAdapter
//
// }
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/ViewPager.kt | 853696116 |
package com.example.practice_musicplayer
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.media.AudioManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.SearchView
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.adapters.MusicAdapter
import com.example.practice_musicplayer.databinding.ActivityMainBinding
import com.example.practice_musicplayer.utils.RetrofitService
import com.example.practice_musicplayer.utils.WaveAnimation
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.simform.refresh.SSPullToRefreshLayout
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.util.ArrayList
import kotlin.system.exitProcess
class MainActivity : AppCompatActivity() {
lateinit var musicAdapter: MusicAdapter
private lateinit var toggle: ActionBarDrawerToggle
private val myBroadcastReceiver = MyBroadcastReceiver()
private val apiService = RetrofitService.getInstance()
companion object {
var songList: ArrayList<MusicClass>? = null
lateinit var recyclerView: RecyclerView
lateinit var musicListSearch: ArrayList<MusicClass>
var isSearching: Boolean = false
@SuppressLint("StaticFieldLeak")
lateinit var binding: ActivityMainBinding
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setTheme(R.style.Base_Theme_Practice_musicPlayer)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
val filter = IntentFilter()
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
filter.addAction(AudioManager.ACTION_HEADSET_PLUG)
registerReceiver(myBroadcastReceiver, filter)
toggle = ActionBarDrawerToggle(this, binding.root, R.string.open, R.string.close)
binding.root.addDrawerListener(toggle)
toggle.syncState()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
getNewSongs()
//for refreshing layout on swipe from top
binding.refreshLayout.setRefreshView(WaveAnimation(this@MainActivity))
binding.refreshLayout.setOnRefreshListener(object :
SSPullToRefreshLayout.OnRefreshListener {
override fun onRefresh() {
CoroutineScope(Dispatchers.Main).launch {
delay(1000)
getNewSongs()
musicAdapter.updateMusicList(songList!!)
Log.d("Begli" , songList.toString())
binding.refreshLayout.setRefreshing(false) // This stops refreshing
}
}
})
binding.navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.navFeedback -> {
Toast.makeText(this, "Feedback", Toast.LENGTH_SHORT).show()
}
R.id.navAbout -> {
Toast.makeText(this, "About", Toast.LENGTH_SHORT).show()
}
R.id.navExit -> {
val builder = MaterialAlertDialogBuilder(this)
builder.setTitle("Exit")
.setMessage("Do you want to close app?")
.setPositiveButton("Yes") { _, _ ->
exitApplication()
}
.setNegativeButton("No") { dialog, _ ->
dialog.dismiss()
}
val customDialog = builder.create()
customDialog.show()
}
}
true
}
}
fun getNewSongs() {
val apiService =
apiService.getNewSongs(
)
apiService?.enqueue(object : Callback<String?> {
override fun onResponse(call: Call<String?>, response: Response<String?>) {
if (response.isSuccessful) {
if (response.body() != null) {
val jsonresponse: String = response.body().toString()
// on below line we are initializing our adapter.
// Log.d("response", jsonresponse.toString())
recycleNewSongs(jsonresponse)
} else {
Log.i(
"onEmptyResponse",
"Returned empty response"
)
}
}
}
override fun onFailure(call: Call<String?>, t: Throwable) {
Log.e(
"ERROR",
t.message.toString()
)
}
})
}
private fun recycleNewSongs(response: String) = try {
val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList()
val obj = JSONObject(response)
val dataArray = obj.getJSONArray("data")
// Log.d("RESPONSE", dataArray.toString())
for (i in 0 until dataArray.length()) {
val dataObject = dataArray.getJSONObject(i)
val musicItem = MusicClass(
id = dataObject.getInt("id"),
date = dataObject.getString("date"),
name = dataObject.getString("name"),
duration = dataObject.getString("duration"),
artist = dataObject.getString("artist"),
coverArtUrl = dataObject.getString("cover_art_url"),
url = dataObject.getString("url")
)
modelRecyclerArrayList.add(musicItem)
}
// Log.d("RESPONSE", modelRecyclerArrayList.toString())
songList = modelRecyclerArrayList
newSongRecycleData(songList!!)
} catch (e: JSONException) {
e.printStackTrace()
}
private fun newSongRecycleData(array: ArrayList<MusicClass>) {
recyclerView = binding.listView
musicAdapter = MusicAdapter(this, array)
recyclerView.adapter = musicAdapter
recyclerView.setItemViewCacheSize(50)
recyclerView.hasFixedSize()
recyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(myBroadcastReceiver)
exitApplication()
}
override fun onResume() {
super.onResume()
if (MusicInterface.musicService != null) binding.nowPlaying.visibility = View.VISIBLE
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (toggle.onOptionsItemSelected(item))
return true
return super.onOptionsItemSelected(item)
}
}
| practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MainActivity.kt | 1139118990 |
package com.example.practice_musicplayer
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.view.KeyEvent
import androidx.core.app.NotificationCompat
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.fragments.NowPlaying
import com.example.practice_musicplayer.utils.ApplicationClass
import com.google.android.exoplayer2.DefaultLoadControl
import com.google.android.exoplayer2.DefaultRenderersFactory
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.upstream.DefaultDataSource
@Suppress("DEPRECATION")
class MusicService : Service(), AudioManager.OnAudioFocusChangeListener {
private var myBinder = MyBinder()
var mediaPlayer: MediaPlayer? = null
private lateinit var mediaSession: MediaSessionCompat
private lateinit var runnable: Runnable
lateinit var audioManager: AudioManager
val broadcastReceiver: MyBroadcastReceiver = MyBroadcastReceiver()
companion object {
lateinit var playPendingIntent: PendingIntent
}
override fun onBind(intent: Intent?): IBinder {
mediaSession = MediaSessionCompat(baseContext, "Music")
return myBinder
}
inner class MyBinder : Binder() {
fun currentService(): MusicService {
return this@MusicService
}
}
@SuppressLint("UnspecifiedImmutableFlag")
fun showNotification(playPauseButton: Int) {
val intent = Intent(baseContext, MusicInterface::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
intent.putExtra("index", MusicInterface.songPosition)
intent.putExtra("class", "Now Playing Notification")
val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
val contentIntent = PendingIntent.getActivity(this, 0, intent, flag)
val prevIntent =
Intent(
baseContext,
MyBroadcastReceiver::class.java
).setAction(ApplicationClass.PREVIOUS)
val prevPendingIntent = PendingIntent.getBroadcast(
baseContext, 3, prevIntent, flag
)
val playIntent =
Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.PLAY)
playPendingIntent = PendingIntent.getBroadcast(
baseContext, 3, playIntent, flag
)
val nextIntent =
Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.NEXT)
val nextPendingIntent = PendingIntent.getBroadcast(
baseContext, 3, nextIntent, flag
)
val exitIntent =
Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.EXIT)
val exitPendingIntent = PendingIntent.getBroadcast(
baseContext, 3, exitIntent, flag
)
createNotificationChannel()
val notificationIntent = Intent(this, MusicInterface::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(this, "12")
.setContentTitle(MusicInterface.musicList[MusicInterface.songPosition].name)
.setContentText(MusicInterface.musicList[MusicInterface.songPosition].artist)
.setSubText(MusicInterface.musicList[MusicInterface.songPosition].name)
.setSmallIcon(R.drawable.music_note)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setStyle(
androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSession.sessionToken)
.setShowActionsInCompactView(0, 1, 2)
)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setOnlyAlertOnce(true)
.addAction(R.drawable.navigate_before_notification, "Previous", prevPendingIntent)
.addAction(playPauseButton, "PlayPause", playPendingIntent)
.addAction(R.drawable.navigate_next_notification, "Next", nextPendingIntent)
.addAction(R.drawable.close_notification, "Exit", exitPendingIntent)
.build()
// val notification = NotificationCompat.Builder(baseContext, ApplicationClass.CHANNEL_ID)
// .setContentTitle(MusicInterface.musicList[MusicInterface.songPosition].name)
// .setContentText(MusicInterface.musicList[MusicInterface.songPosition].artist)
// .setSubText(MusicInterface.musicList[MusicInterface.songPosition].date)
// .setSmallIcon(R.drawable.music_note)
// .setStyle(
// androidx.media.app.NotificationCompat.MediaStyle()
// .setMediaSession(mediaSession.sessionToken)
// .setShowActionsInCompactView(0, 1, 2)
// ).setPriority(NotificationCompat.PRIORITY_HIGH)
// .setSilent(true)
// .setContentIntent(contentIntent)
// .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setOnlyAlertOnce(true)
// .addAction(R.drawable.navigate_before_notification, "Previous", prevPendingIntent)
// .addAction(playPauseButton, "PlayPause", playPendingIntent)
// .build()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val playbackSpeed = if (MusicInterface.isPlaying) 1F else 0F
mediaSession.setMetadata(
MediaMetadataCompat.Builder()
.putLong(
MediaMetadataCompat.METADATA_KEY_DURATION,
mediaPlayer!!.duration.toLong()
)
.build()
)
val playBackState = PlaybackStateCompat.Builder()
.setState(
PlaybackStateCompat.STATE_PLAYING,
mediaPlayer!!.currentPosition.toLong(),
playbackSpeed
)
.setActions(
PlaybackStateCompat.ACTION_SEEK_TO
or PlaybackStateCompat.ACTION_SKIP_TO_NEXT
or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
or PlaybackStateCompat.ACTION_PLAY_PAUSE
)
.build()
mediaSession.setPlaybackState(playBackState)
mediaSession.isActive = true
mediaSession.setCallback(object : MediaSessionCompat.Callback() {
override fun onMediaButtonEvent(mediaButtonEvent: Intent): Boolean {
val event =
mediaButtonEvent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
if (event != null) {
if (event.action == KeyEvent.ACTION_DOWN) {
when (event.keyCode) {
KeyEvent.KEYCODE_MEDIA_PAUSE -> {
if (mediaPlayer != null) {
if (MusicInterface.isPlaying) {
//pause music
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
MusicInterface.isPlaying = false
mediaPlayer!!.pause()
showNotification(R.drawable.play_notification)
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
} else {
//play music
MusicInterface.binding.interfacePlay.setImageResource(
R.drawable.pause
)
MusicInterface.isPlaying = true
mediaPlayer!!.start()
showNotification(R.drawable.pause_notification)
NowPlaying.binding.fragmentButton.setImageResource(
R.drawable.pause_now
)
}
}
}
KeyEvent.KEYCODE_MEDIA_NEXT -> {
broadcastReceiver.prevNextMusic(increment = true, baseContext)
MusicInterface.counter--
}
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {
broadcastReceiver.prevNextMusic(increment = false, baseContext)
}
}
return true
}
}
return false
}
override fun onSeekTo(pos: Long) {
super.onSeekTo(pos)
mediaPlayer!!.seekTo(pos.toInt())
val playBackStateNew = PlaybackStateCompat.Builder()
.setState(
PlaybackStateCompat.STATE_PLAYING,
mediaPlayer!!.currentPosition.toLong(),
playbackSpeed
)
.setActions(PlaybackStateCompat.ACTION_SEEK_TO)
.build()
mediaSession.setPlaybackState(playBackStateNew)
}
})
}
startForeground(1, notification)
}
fun initSong() {
try {
if (mediaPlayer == null) mediaPlayer = MediaPlayer()
MusicInterface.musicService!!.mediaPlayer!!.reset()
MusicInterface.musicService!!.mediaPlayer!!.setDataSource(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl)
MusicInterface.musicService!!.mediaPlayer!!.prepare()
MusicInterface.musicService!!.showNotification(R.drawable.pause_notification)
MusicInterface.binding.interfacePlay.setImageResource((R.drawable.pause))
} catch (e: Exception) {
return
}
}
fun seekBarHandler() {
runnable = Runnable {
MusicInterface.binding.interfaceSeekStart.text =
formatDuration(mediaPlayer!!.currentPosition.toLong())
MusicInterface.binding.seekbar.progress = mediaPlayer!!.currentPosition
Handler(Looper.getMainLooper()).postDelayed(runnable, 200)
}
Handler(Looper.getMainLooper()).postDelayed(runnable, 0)
}
override fun onAudioFocusChange(focusChange: Int) {
if (focusChange <= 0) {
//pause music
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
MusicInterface.isPlaying = false
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
mediaPlayer!!.pause()
showNotification(R.drawable.play_notification)
} else {
//play music
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
MusicInterface.isPlaying = true
mediaPlayer!!.start()
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)
showNotification(R.drawable.pause_notification)
}
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel("12", "Foreground Service Channel",
NotificationManager.IMPORTANCE_LOW)
val manager = getSystemService(NotificationManager::class.java)
manager!!.createNotificationChannel(serviceChannel)
}
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MusicService.kt | 4273669195 |
package com.example.practice_musicplayer.fragments
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.practice_musicplayer.MusicClass
import com.example.practice_musicplayer.R
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.adapters.AdapterViewPager
import com.example.practice_musicplayer.databinding.FragmentExamplePlayingBinding
import com.example.practice_musicplayer.databinding.FragmentNowPlayingBinding
import com.example.practice_musicplayer.getImageArt
import com.example.practice_musicplayer.setSongPosition
import com.example.practice_musicplayer.utils.OnSwipeTouchListener
import com.example.practice_musicplayer.utils.RetrofitService
import com.example.practice_musicplayer.utils.ViewPagerExtensions.addCarouselEffect
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.ArrayList
@Suppress("DEPRECATION")
class ExamplePlaying : Fragment() {
lateinit var viewPagerAdapter: AdapterViewPager
private val apiService = RetrofitService.getInstance()
private var songList: ArrayList<MusicClass>? = null
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var binding: FragmentExamplePlayingBinding
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
binding = FragmentExamplePlayingBinding.inflate(inflater, container, false)
val view: View = binding.root
binding.root.visibility = View.VISIBLE
getNewSongs()
return view
}
private fun getNewSongs() {
val apiService =
apiService.getNewSongs(
)
apiService?.enqueue(object : Callback<String?> {
override fun onResponse(call: Call<String?>, response: Response<String?>) {
if (response.isSuccessful) {
if (response.body() != null) {
val jsonresponse: String = response.body().toString()
// on below line we are initializing our adapter.
Log.d("response", jsonresponse)
recycleNewSongs(jsonresponse)
} else {
Log.i(
"onEmptyResponse",
"Returned empty response"
)
}
}
}
override fun onFailure(call: Call<String?>, t: Throwable) {
Log.e(
"ERROR",
t.message.toString()
)
}
})
}
private fun recycleNewSongs(response: String) = try {
val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList()
val obj = JSONObject(response)
val dataArray = obj.getJSONArray("data")
// Log.d("RESPONSE", dataArray.toString())
for (i in 0 until dataArray.length()) {
val dataObject = dataArray.getJSONObject(i)
val musicItem = MusicClass(
id = dataObject.getInt("id"),
date = dataObject.getString("date"),
name = dataObject.getString("name"),
duration = dataObject.getString("duration"),
artist = dataObject.getString("artist"),
coverArtUrl = dataObject.getString("cover_art_url"),
url = dataObject.getString("url")
)
modelRecyclerArrayList.add(musicItem)
}
// Log.d("RESPONSE", modelRecyclerArrayList.toString())
songList = modelRecyclerArrayList
// newSongRecycleData(songList!!)
} catch (e: JSONException) {
e.printStackTrace()
}
// private fun newSongRecycleData(array: ArrayList<MusicClass>) {
//
// binding.viewPager.addCarouselEffect()
// viewPagerAdapter = AdapterViewPager(requireContext(), array)
// binding.viewPager.adapter = viewPagerAdapter
//
// }
@SuppressLint("ClickableViewAccessibility")
override fun onResume() {
super.onResume()
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/fragments/ExamplePlaying.kt | 2718263673 |
package com.example.practice_musicplayer.fragments
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.practice_musicplayer.MainActivity
import com.example.practice_musicplayer.R
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.databinding.FragmentNowPlayingBinding
import com.example.practice_musicplayer.getImageArt
import com.example.practice_musicplayer.getNewSongs
import com.example.practice_musicplayer.setSongPosition
import com.example.practice_musicplayer.utils.OnSwipeTouchListener
@Suppress("DEPRECATION")
class NowPlaying : Fragment() {
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var binding: FragmentNowPlayingBinding
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
binding = FragmentNowPlayingBinding.inflate(inflater, container, false)
val view: View = binding.root
binding.root.visibility = View.GONE
binding.fragmentButton.setOnClickListener {
if (MusicInterface.isPlaying) pauseMusic()
else playMusic()
}
// Inflate the layout for this fragment
return view
}
@SuppressLint("ClickableViewAccessibility")
override fun onResume() {
super.onResume()
if (MusicInterface.musicService != null) {
binding.root.visibility = View.VISIBLE
binding.fragmentTitle.isSelected = true
binding.root.setOnTouchListener(object : OnSwipeTouchListener(requireContext()) {
override fun onSingleClick() {
openActivity()
}
override fun onSwipeTop() {
Log.d(ContentValues.TAG, "onSwipeTop: Performed")
openActivity()
}
override fun onSwipeLeft() {
nextPrevMusic(increment = true)
}
override fun onSwipeRight() {
nextPrevMusic(increment = false)
}
})
Log.e("musiclist", MusicInterface.musicList.toString())
Glide.with(this)
.load(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl)
.apply(
RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop()
).into(binding.fragmentImage)
binding.fragmentTitle.text =
MusicInterface.musicList[MusicInterface.songPosition].name
binding.fragmentAlbumName.text =
MusicInterface.musicList[MusicInterface.songPosition].artist
if (MusicInterface.isPlaying) binding.fragmentButton.setImageResource(R.drawable.pause_now)
else binding.fragmentButton.setImageResource(R.drawable.play_now)
}
}
private fun playMusic() {
MusicInterface.musicService!!.audioManager.requestAudioFocus(
MusicInterface.musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN
)
MusicInterface.isPlaying = true
binding.fragmentButton.setImageResource(R.drawable.pause_now)
MusicInterface.musicService!!.showNotification(R.drawable.pause_notification)
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
MusicInterface.musicService!!.mediaPlayer!!.start()
}
private fun pauseMusic() {
MusicInterface.musicService!!.audioManager.abandonAudioFocus(MusicInterface.musicService)
MusicInterface.isPlaying = false
MusicInterface.musicService!!.mediaPlayer!!.pause()
MusicInterface.musicService!!.showNotification(R.drawable.play_notification)
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
binding.fragmentButton.setImageResource(R.drawable.play_now)
}
private fun nextPrevMusic(increment: Boolean) {
setSongPosition(increment = increment)
MusicInterface.musicService!!.initSong()
Glide.with(requireContext())
.load(getImageArt(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl))
.apply(
RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop()
).into(binding.fragmentImage)
binding.fragmentTitle.text =
MusicInterface.musicList[MusicInterface.songPosition].name
binding.fragmentAlbumName.text =
MusicInterface.musicList[MusicInterface.songPosition].artist
playMusic()
}
fun openActivity() {
val intent = Intent(requireContext(), MusicInterface::class.java)
intent.putExtra("index", MusicInterface.songPosition)
intent.putExtra("class", "Now playing")
ContextCompat.startActivity(requireContext(), intent, null)
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/fragments/NowPlaying.kt | 882773309 |
package com.example.practice_musicplayer
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.practice_musicplayer.adapters.AdapterViewPager
import com.example.practice_musicplayer.adapters.MusicAdapter
import com.example.practice_musicplayer.databinding.ActivitySlidingBinding
import com.example.practice_musicplayer.databinding.ItemLargeCarouselBinding
import com.example.practice_musicplayer.utils.RetrofitService
import com.sothree.slidinguppanel.SlidingUpPanelLayout
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
open class SlidingActivity : AppCompatActivity() {
private lateinit var binding: ActivitySlidingBinding
lateinit var viewPagerAdapter: AdapterViewPager
private val apiService = RetrofitService.getInstance()
private var songList: ArrayList<MusicClass>? = null
lateinit var recyclerView: RecyclerView
lateinit var musicAdapter: MusicAdapter
private var initialSlide = true
companion object {
var statePanel: Boolean = true
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySlidingBinding.inflate(layoutInflater)
setContentView(binding.root)
val slidingLayout: SlidingUpPanelLayout = findViewById(R.id.sliding_layout)
// Initially hide the sliding panel
slidingLayout.panelState = SlidingUpPanelLayout.PanelState.HIDDEN
// Convert DP to pixels
val pixels = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
65f,
resources.displayMetrics
).toInt()
binding.btnSlide.setOnClickListener {
// Slide up the panel when the button is clicked
// slidingLayout.panelState = SlidingUpPanelLayout.PanelState.EXPANDED
if (initialSlide) {
// If it's the first slide, set the panel height
slidingLayout.panelState = SlidingUpPanelLayout.PanelState.EXPANDED
initialSlide = false
} else {
// Toggle the sliding panel when the button is clicked
slidingLayout.panelState =
if (slidingLayout.panelState == SlidingUpPanelLayout.PanelState.COLLAPSED)
SlidingUpPanelLayout.PanelState.EXPANDED
else
SlidingUpPanelLayout.PanelState.COLLAPSED
}
}
// Set up the Sliding UpPanelLayout
slidingLayout.addPanelSlideListener(object : SlidingUpPanelLayout.PanelSlideListener {
@SuppressLint("NotifyDataSetChanged")
override fun onPanelSlide(panel: View?, slideOffset: Float) {
// Do something when the panel is sliding
Log.e("panel", "offset $slideOffset")
// Iterate through all items in the ViewPager and update the visibility of smalCard
if (slideOffset <= 0.5){
statePanel = false
} else {
statePanel = true
}
viewPagerAdapter.notifyDataSetChanged()
//
Log.e("state", statePanel.toString())
}
@SuppressLint("NotifyDataSetChanged")
override fun onPanelStateChanged(
panel: View?,
previousState: SlidingUpPanelLayout.PanelState?,
newState: SlidingUpPanelLayout.PanelState?,
) {
// Do something when the panel state changes
Log.e("panel", "Hide")
if (newState == SlidingUpPanelLayout.PanelState.COLLAPSED) {
// If the panel is collapsed, set it to expanded with the desired height
slidingLayout.panelHeight = pixels
}
}
})
getNewSongs()
}
private fun getNewSongs() {
val apiService =
apiService.getNewSongs(
)
apiService?.enqueue(object : Callback<String?> {
override fun onResponse(call: Call<String?>, response: Response<String?>) {
if (response.isSuccessful) {
if (response.body() != null) {
val jsonresponse: String = response.body().toString()
// on below line we are initializing our adapter.
Log.d("response", jsonresponse)
recycleNewSongs(jsonresponse)
} else {
Log.i(
"onEmptyResponse",
"Returned empty response"
)
}
}
}
override fun onFailure(call: Call<String?>, t: Throwable) {
Log.e(
"ERROR",
t.message.toString()
)
}
})
}
private fun recycleNewSongs(response: String) = try {
val modelRecyclerArrayList: ArrayList<MusicClass> = ArrayList()
val obj = JSONObject(response)
val dataArray = obj.getJSONArray("data")
// Log.d("RESPONSE", dataArray.toString())
for (i in 0 until dataArray.length()) {
val dataObject = dataArray.getJSONObject(i)
val musicItem = MusicClass(
id = dataObject.getInt("id"),
date = dataObject.getString("date"),
name = dataObject.getString("name"),
duration = dataObject.getString("duration"),
artist = dataObject.getString("artist"),
coverArtUrl = dataObject.getString("cover_art_url"),
url = dataObject.getString("url")
)
modelRecyclerArrayList.add(musicItem)
}
// Log.d("RESPONSE", modelRecyclerArrayList.toString())
songList = modelRecyclerArrayList
newSongViewPagerData(songList!!)
newSongRecycleData(songList!!)
} catch (e: JSONException) {
e.printStackTrace()
}
private fun newSongViewPagerData(array: ArrayList<MusicClass>) {
viewPagerAdapter = AdapterViewPager(this, array)
binding.viewPager.adapter = viewPagerAdapter
}
private fun newSongRecycleData(array: ArrayList<MusicClass>) {
recyclerView = binding.recycleSliding
musicAdapter = MusicAdapter(this, array)
recyclerView.adapter = musicAdapter
recyclerView.setItemViewCacheSize(50)
recyclerView.hasFixedSize()
recyclerView.layoutManager = LinearLayoutManager(this@SlidingActivity)
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/SlidingActivity.kt | 138562788 |
package com.example.practice_musicplayer
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.util.Log
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.fragments.NowPlaying
import com.example.practice_musicplayer.utils.ApplicationClass
@Suppress("DEPRECATION")
class MyBroadcastReceiver : BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
ApplicationClass.PREVIOUS -> {
prevNextMusic(increment = false, context = context!!)
}
ApplicationClass.PLAY -> {
if (MusicInterface.isPlaying) pauseMusic() else playMusic()
}
ApplicationClass.NEXT -> {
prevNextMusic(increment = true, context = context!!)
MusicInterface.counter--
}
ApplicationClass.EXIT -> {
exitApplicationNotification()
}
/*
AudioManager.ACTION_HEADSET_PLUG -> {
val state = intent.getIntExtra("state", -1)
if (state == 0) {
pauseMusic()
} else{
Log.d(TAG, "onReceive: HeadSet Plugged")
}
}
*/
BluetoothAdapter.ACTION_STATE_CHANGED -> {
val state =
intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
Log.d(ContentValues.TAG, "onReceive: ${state.toString()}")
when (state) {
BluetoothAdapter.STATE_OFF -> {
pauseMusic()
}
BluetoothAdapter.STATE_TURNING_OFF -> {
pauseMusic()
}
}
}
}
}
private fun playMusic() {
MusicInterface.musicService!!.audioManager.requestAudioFocus(
MusicInterface.musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN
)
MusicInterface.isPlaying = true
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
MusicInterface.musicService!!.mediaPlayer!!.start()
MusicInterface.musicService!!.showNotification(R.drawable.pause_notification)
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)
}
fun prevNextMusic(increment: Boolean, context: Context) {
try {
setSongPosition(increment = increment)
MusicInterface.musicService!!.initSong()
Glide.with(context)
.load(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl)
.apply(
RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop()
).into(MusicInterface.binding.interfaceCover)
MusicInterface.binding.interfaceSongName.text =
MusicInterface.musicList[MusicInterface.songPosition].name
MusicInterface.binding.interfaceArtistName.text =
MusicInterface.musicList[MusicInterface.songPosition].artist
Glide.with(context)
.load(MusicInterface.musicList[MusicInterface.songPosition].coverArtUrl)
.apply(
RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop()
).into(NowPlaying.binding.fragmentImage)
NowPlaying.binding.fragmentTitle.text =
MusicInterface.musicList[MusicInterface.songPosition].name
NowPlaying.binding.fragmentAlbumName.text =
MusicInterface.musicList[MusicInterface.songPosition].artist
playMusic()
} catch (e: Exception) {
Log.e("AdapterView", e.toString())
}
}
private fun pauseMusic() {
MusicInterface.musicService!!.audioManager.abandonAudioFocus(MusicInterface.musicService)
MusicInterface.isPlaying = false
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
MusicInterface.musicService!!.mediaPlayer!!.pause()
MusicInterface.musicService!!.showNotification(R.drawable.play_notification)
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MyBroadcastReceiver.kt | 126275512 |
@file:Suppress("DEPRECATION")
package com.example.practice_musicplayer
import android.content.ContentValues
import android.content.Intent
import android.content.pm.ServiceInfo
import android.graphics.Bitmap
import android.graphics.Color
import android.media.MediaMetadataRetriever
import android.util.Log
import androidx.core.app.ServiceCompat
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.utils.RetrofitService
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt
import kotlin.random.Random
import kotlin.system.exitProcess
data class MusicClass(
val id: Int,
val date: String,
var name: String,
val duration: String,
var artist: String,
var coverArtUrl: String,
var url: String
)
val usedNumber = mutableSetOf<Int>()
class Playlist {
lateinit var name: String
lateinit var playlist: ArrayList<MusicClass>
lateinit var createdBy: String
lateinit var createdOn: String
}
class MusicPlaylist {
var ref: ArrayList<Playlist> = ArrayList()
}
fun exitApplication() {
exitProcess(1)
}
fun getImageArt(path: String): ByteArray? {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(path)
return retriever.embeddedPicture
}
fun getMainColor(img: Bitmap): Int {
val newImg = Bitmap.createScaledBitmap(img, 1, 1, true)
val color = newImg.getPixel(0, 0)
newImg.recycle()
return manipulateColor(color, 0.4.toFloat())
}
fun manipulateColor(color: Int, factor: Float): Int {
val a: Int = Color.alpha(color)
val r = (Color.red(color) * factor).roundToInt()
val g = (Color.green(color) * factor).roundToInt()
val b = (Color.blue(color) * factor).roundToInt()
return Color.argb(
a,
r.coerceAtMost(255),
g.coerceAtMost(255),
b.coerceAtMost(255)
)
}
fun exitApplicationNotification() {
// if (MusicInterface.isPlaying) {
// val musicInterface = MusicInterface()
// musicInterface.pauseMusic()
// }
Log.e("serStop", MusicInterface.musicService.toString())
MusicInterface.musicService!!.stopForeground(true)
// MusicInterface.myService!!.stopForeground(true)
}
fun formatDuration(duration: Long): String {
val minutes = TimeUnit.MINUTES.convert(duration, TimeUnit.MILLISECONDS)
val seconds = (TimeUnit.SECONDS.convert(
duration, TimeUnit.MILLISECONDS
) - minutes * TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES))
return String.format("%02d:%02d", minutes, seconds)
}
fun shuffleSongs() {
var newSong: Int = MusicInterface.songPosition
checkIfListIsFull(usedNumber)
Log.d(ContentValues.TAG, "shuffleSongs: " + usedNumber.size)
while (newSong == MusicInterface.songPosition) {
newSong = getRandomNumber(MusicInterface.musicList.size)
}
MusicInterface.songPosition = newSong
}
fun getRandomNumber(max: Int): Int {
val random = Random
var number = random.nextInt(max + 1)
while (usedNumber.contains(number)) {
number = random.nextInt(max + 1)
}
usedNumber.add(number)
return number
}
fun checkIfListIsFull(list: MutableSet<Int>) {
if (list.size.toInt() == MusicInterface.musicList.size) {
list.clear()
}
}
fun setSongPosition(increment: Boolean) {
if (!MusicInterface.isRepeating) {
if (increment) {
if (MusicInterface.isShuffling && MusicInterface.counter == 0) {
shuffleSongs()
} else {
if (MusicInterface.musicList.size - 1 == MusicInterface.songPosition) {
MusicInterface.songPosition = 0
} else ++MusicInterface.songPosition
}
} else {
if (0 == MusicInterface.songPosition) MusicInterface.songPosition =
MusicInterface.musicList.size - 1
else --MusicInterface.songPosition
}
}
}
fun getNewSongs() {
val api_Service = RetrofitService.getInstance()
val apiService =
api_Service.getNewSongs(
)
apiService?.enqueue(object : Callback<String?> {
override fun onResponse(call: Call<String?>, response: Response<String?>) {
if (response.isSuccessful) {
if (response.body() != null) {
val jsonresponse: String = response.body().toString()
// on below line we are initializing our adapter.
// Log.d("response", jsonresponse.toString())
recycleNewSongs(jsonresponse)
} else {
Log.i(
"onEmptyResponse",
"Returned empty response"
)
}
}
}
override fun onFailure(call: Call<String?>, t: Throwable) {
Log.e(
"ERROR",
t.message.toString()
)
}
})
}
fun recycleNewSongs(response: String) = try {
val modelRecyclerArrayList: java.util.ArrayList<MusicClass> = java.util.ArrayList()
val obj = JSONObject(response)
val dataArray = obj.getJSONArray("data")
// Log.d("RESPONSE", dataArray.toString())
for (i in 0 until dataArray.length()) {
val dataObject = dataArray.getJSONObject(i)
val musicItem = MusicClass(
id = dataObject.getInt("id"),
date = dataObject.getString("date"),
name = dataObject.getString("name"),
duration = dataObject.getString("duration"),
artist = dataObject.getString("artist"),
coverArtUrl = dataObject.getString("cover_art_url"),
url = dataObject.getString("url")
)
modelRecyclerArrayList.add(musicItem)
}
// Log.d("RESPONSE", modelRecyclerArrayList.toString())
MainActivity.songList = modelRecyclerArrayList
} catch (e: JSONException) {
e.printStackTrace()
}
| practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MusicClass.kt | 3430967671 |
package com.example.practice_musicplayer.utils
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import com.simform.refresh.SSAnimationView
import kotlin.math.sin
// This is a demo view in which user can set any animation or
// just make it blank and set Gif animation using setGifAnimation() method on SSPullToRefreshLayout
class WaveAnimation(context: Context): SSAnimationView(context) {
private var amplitude = 22f.toDp() // scale
private var speed = 0f
private val path = Path()
private var paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var animator: ValueAnimator? = null
override fun onDraw(c: Canvas) = c.drawPath(path, paint)
private fun createAnimator(): ValueAnimator {
return ValueAnimator.ofFloat(0f, Float.MAX_VALUE).apply {
repeatCount = ValueAnimator.INFINITE
addUpdateListener {
speed -= WAVE_SPEED
createPath()
invalidate()
}
}
}
private fun createPath() {
path.reset()
paint.color = Color.parseColor("#00F15E")
path.moveTo(0f, height.toFloat())
path.lineTo(0f, amplitude)
path.lineTo(0f, amplitude - 10)
var i = 0
while (i < width + 10) {
val wx = i.toFloat()
val sinComponent = sin((i + 10) * Math.PI / WAVE_AMOUNT_ON_SCREEN + speed).toFloat()
val wy = amplitude * (2 + sinComponent)
path.lineTo(wx, wy)
i += 10
}
path.lineTo(width.toFloat(), height.toFloat())
path.close()
}
override fun onDetachedFromWindow() {
animator?.cancel()
super.onDetachedFromWindow()
}
companion object {
const val WAVE_SPEED = 0.25f
const val WAVE_AMOUNT_ON_SCREEN = 350
}
private fun Float.toDp() = this * context.resources.displayMetrics.density
override fun reset() {
}
override fun refreshing() {
}
override fun refreshComplete() {
animator?.cancel()
}
override fun pullToRefresh() {
animator = createAnimator().apply {
start()
}
}
override fun releaseToRefresh() {
}
override fun pullProgress(pullDistance: Float, pullProgress: Float) {
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/WaveAnimation.kt | 149983999 |
package com.example.practice_musicplayer.utils
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.http.GET
interface RetrofitService {
// @GET("api/v1/song?sort=date&order=desc&max=10")
// fun getMainPage(): Call<SongResponse?>?
@GET("api/v1/song?sort=date&order=desc&max=10")
fun getNewSongs(): Call<String?>?
@GET("api/v1/song?sort=date&order=desc&max=10&artistId=47%2C48%2C106%2C102%2C17%2C44%2C37%2C70%2C8%2C49%2C57%2C4%2C35%2C38%2C46%2C53%2C16%2C51%2C55%2C52%2C61%2C24%2C15%2C127%2C460%2C790%2C104")
fun getTrendSongs(): Call<String?>?
@GET("api/v1/video?sort=date&order=desc&videoTypeId=1")
fun getClips(): Call<String?>?
companion object {
var retrofitService: RetrofitService? = null
fun getInstance(): RetrofitService {
if (retrofitService == null) {
val retrofit = Retrofit.Builder()
.baseUrl("https://aydym.com/")
.addConverterFactory(ScalarsConverterFactory.create())
// .addConverterFactory(GsonConverterFactory.create())
.build()
retrofitService = retrofit.create(RetrofitService::class.java)
}
return retrofitService!!
}
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/RetrofitService.kt | 4159014262 |
package com.example.practice_musicplayer.utils
class DpData {
val dummyData = listOf(
"Hello Developers",
"Hope, you are all fine!",
"Sohaib here!",
"Enjoy this new feature.",
"I made it pretty easier for you by adding an extension function."
)
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/DpData.kt | 2629802236 |
package com.example.practice_musicplayer.utils
import android.annotation.SuppressLint
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
class ApplicationClass : Application() {
companion object {
const val CHANNEL_ID = "12"
const val NEXT = "next"
const val PREVIOUS = "previous"
const val PLAY = "play"
const val EXIT = "exit"
}
@SuppressLint("ObsoleteSdkInt")
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel =
NotificationChannel(CHANNEL_ID, "Now playing", NotificationManager.IMPORTANCE_HIGH)
notificationChannel.description = "Channel for showing playing song"
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/ApplicationClass.kt | 380289635 |
package com.example.practice_musicplayer.utils
import android.annotation.SuppressLint
import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import kotlin.math.abs
open class OnSwipeTouchListener(ctx: Context) : View.OnTouchListener {
private val gestureDetector: GestureDetector
companion object {
private const val SWIPE_THRESHOLD = 300
private const val SWIPE_VELOCITY_THRESHOLD = 300
}
init {
gestureDetector = GestureDetector(ctx, GestureListener())
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(event)
}
private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
onSingleClick()
return super.onSingleTapConfirmed(e)
}
override fun onFling(
e1: MotionEvent,
e2: MotionEvent,
velocityX: Float,
velocityY: Float
): Boolean {
var result = false
try {
val diffY = e2.y - e1.y
val diffX = e2.x - e1.x
if (abs(diffX) > abs(diffY)) {
if (abs(diffX) > SWIPE_THRESHOLD && abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight()
} else {
onSwipeLeft()
}
result = true
}
} else if (abs(diffY) > abs(diffX)) {
if (abs(diffY) > SWIPE_THRESHOLD && abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY < 0) {
onSwipeTop()
} else if (diffY > 0) {
onSwipeDown()
}
result = true
}
}
} catch (exception: Exception) {
exception.printStackTrace()
}
return result
}
}
open fun onSwipeRight() {}
open fun onSingleClick() {}
open fun onSwipeLeft() {}
open fun onSwipeTop() {}
open fun onSwipeDown() {}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/OnSwipeTouchListener.kt | 2997182530 |
package com.example.practice_musicplayer.utils
import android.content.res.Resources
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.CompositePageTransformer
import androidx.viewpager2.widget.MarginPageTransformer
import androidx.viewpager2.widget.ViewPager2
import kotlin.math.abs
object ViewPagerExtensions {
fun ViewPager2.addCarouselEffect(enableZoom: Boolean = true) {
clipChildren = false // No clipping the left and right items
clipToPadding = false // Show the viewpager in full width without clipping the padding
offscreenPageLimit = 3 // Render the left and right items
(getChildAt(0) as RecyclerView).overScrollMode = RecyclerView.OVER_SCROLL_NEVER // Remove the scroll effect
val compositePageTransformer = CompositePageTransformer()
compositePageTransformer.addTransformer(MarginPageTransformer((20 * Resources.getSystem().displayMetrics.density).toInt()))
if (enableZoom) {
compositePageTransformer.addTransformer { page, position ->
val r = 1 - abs(position)
page.scaleY = (0.80f + r * 0.20f)
}
}
setPageTransformer(compositePageTransformer)
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/utils/ViewPagerExtensions.kt | 2890470067 |
package com.example.practice_musicplayer
import android.annotation.SuppressLint
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.pm.ServiceInfo
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.Settings
import android.support.v4.media.session.MediaSessionCompat
import androidx.annotation.RequiresApi
import androidx.core.app.ServiceCompat
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.fragments.NowPlaying
import com.example.practice_musicplayer.utils.ApplicationClass
@Suppress("DEPRECATION")
class MyService : Service(), AudioManager.OnAudioFocusChangeListener {
var mediaPlayer: MediaPlayer? = null
private var audioUrl: String? = null
private var myBinder = MyBinder()
private val channelid = "3"
lateinit var audioManager: AudioManager
private lateinit var mediaSession: MediaSessionCompat
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate() {
super.onCreate()
mediaPlayer = MediaPlayer()
createNotificationChanel()
}
override fun onBind(intent: Intent?): IBinder {
mediaSession = MediaSessionCompat(baseContext, "Music")
return myBinder
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
playAudio()
showNotification()
return START_STICKY
}
private fun playAudio() {
mediaPlayer?.apply {
reset()
setDataSource(MusicInterface.musicUrl)
prepareAsync()
setOnPreparedListener { start() }
}
initSong()
}
@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("UnspecifiedImmutableFlag", "InlinedApi")
fun showNotification() {
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent =
PendingIntent.getActivity(this, 3, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
val exitIntent =
Intent(baseContext, MyBroadcastReceiver::class.java).setAction(ApplicationClass.EXIT)
val exitPendingIntent = PendingIntent.getBroadcast(
baseContext, 3, exitIntent, flag
)
val notification = Notification
.Builder(this, channelid)
.setContentText("Music Player")
.setSmallIcon(R.drawable.play)
.setContentIntent(pendingIntent)
.build()
startForeground(
3, notification,
)
}
inner class MyBinder : Binder() {
fun currentService(): MyService {
return this@MyService
}
}
private fun createNotificationChanel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
channelid, "Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager!!.createNotificationChannel(serviceChannel)
}
}
fun initSong() {
try {
if (mediaPlayer == null) mediaPlayer = MediaPlayer()
MusicInterface.myService?.let {
it.mediaPlayer!!.reset()
it.mediaPlayer!!.setDataSource(MusicInterface.musicList[MusicInterface.songPosition].url)
it.mediaPlayer!!.prepare()
it.showNotification()
MusicInterface.binding.interfacePlay.setImageResource((R.drawable.pause))
}
} catch (e: Exception) {
e.printStackTrace() // Log the exception for debugging
}
}
override fun onDestroy() {
super.onDestroy()
mediaPlayer!!.stop()
}
override fun onAudioFocusChange(focusChange: Int) {
if (focusChange <= 0) {
//pause music
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.play)
MusicInterface.isPlaying = false
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
mediaPlayer!!.pause()
showNotification()
} else {
//play music
MusicInterface.binding.interfacePlay.setImageResource(R.drawable.pause)
MusicInterface.isPlaying = true
mediaPlayer!!.start()
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)
showNotification()
}
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/MyService.kt | 1665712383 |
package com.example.practice_musicplayer.adapters
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.practice_musicplayer.MainActivity
import com.example.practice_musicplayer.MusicClass
import com.example.practice_musicplayer.R
import com.example.practice_musicplayer.activities.MusicInterface
import com.example.practice_musicplayer.databinding.SingleLayoutBinding
import com.example.practice_musicplayer.formatDuration
import com.google.android.material.snackbar.Snackbar
class MusicAdapter(
private val context: Context,
private var musicList: ArrayList<MusicClass>,
private val playlistDetails: Boolean = false,
private val selectionActivity: Boolean = false,
) :
RecyclerView.Adapter<MusicAdapter.MyHolder>() {
class MyHolder(binding: SingleLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
val titleView = binding.titleView
val albumName = binding.albumName
val imageView = binding.imageView
val duration = binding.duration
val root = binding.root
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
return MyHolder(
SingleLayoutBinding.inflate(
LayoutInflater.from(
context
), parent, false
)
)
}
override fun onBindViewHolder(holder: MyHolder, position: Int) {
holder.titleView.text = musicList[position].name
holder.albumName.text = musicList[position].artist
holder.duration.text = musicList[position].duration
val myOptions = RequestOptions()
.centerCrop()
.override(100, 100)
Glide
.with(context)
.applyDefaultRequestOptions(myOptions)
.load(musicList[position].coverArtUrl)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.error(R.drawable.image_as_cover)
.into(holder.imageView)
when {
playlistDetails -> {
holder.root.setOnClickListener {
Toast.makeText(context, "play list details", Toast.LENGTH_SHORT).show()
sendIntent(position = position, parameter = "PlaylistDetailsAdapter")
}
}
else -> {
holder.itemView.setOnClickListener {
if (MainActivity.isSearching) {
sendIntent(position = position, parameter = "MusicAdapterSearch")
} else {
sendIntent(position = position, parameter = "MusicAdapter")
}
}
}
}
}
override fun getItemCount(): Int {
return musicList.size
}
fun updateMusicList(searchList: ArrayList<MusicClass>) {
musicList = ArrayList()
musicList.addAll(searchList)
notifyDataSetChanged()
}
private fun sendIntent(position: Int, parameter: String) {
val intent = Intent(context, MusicInterface::class.java)
intent.putExtra("index", position)
intent.putExtra("class", parameter)
ContextCompat.startActivity(context, intent, null)
}
}
| practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/adapters/MusicAdapter.kt | 2542009630 |
package com.example.practice_musicplayer.adapters
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.practice_musicplayer.MusicClass
import com.example.practice_musicplayer.R
import com.example.practice_musicplayer.SlidingActivity
import com.example.practice_musicplayer.databinding.ItemLargeCarouselBinding
import com.google.android.material.card.MaterialCardView
class AdapterViewPager(
private val context: Context,
private var musicList: ArrayList<MusicClass>,
) :
RecyclerView.Adapter<AdapterViewPager.MyHolder>() {
class MyHolder(binding: ItemLargeCarouselBinding) : RecyclerView.ViewHolder(binding.root) {
val songNameUp = binding.mtvItem
val songName = binding.songName
val singerName = binding.singerName
val imgSmall = binding.imgSmall
val imgLarge = binding.imgLarge
val root = binding.root
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
return MyHolder(
ItemLargeCarouselBinding.inflate(
LayoutInflater.from(
context
), parent, false
)
)
}
@SuppressLint("CutPasteId", "NotifyDataSetChanged")
override fun onBindViewHolder(holder: MyHolder, position: Int) {
holder.itemView.findViewById<MaterialCardView>(R.id.smalCard).visibility =
if (SlidingActivity.statePanel) View.GONE else View.VISIBLE
holder.songNameUp.text = musicList[position].name
holder.songName.text = musicList[position].name
holder.singerName.text = musicList[position].artist
val optionSmall = RequestOptions()
.centerCrop()
.override(100, 100)
Glide
.with(context)
.applyDefaultRequestOptions(optionSmall)
.load(musicList[position].coverArtUrl)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.error(R.drawable.image_as_cover)
.into(holder.imgSmall)
val otionsLarge = RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888) // Use higher quality ARGB_8888 format
.diskCacheStrategy(DiskCacheStrategy.ALL) // Cache both original and transformed images
.override(500, 500) // Load the original image size
Glide
.with(context)
.load(musicList[position].coverArtUrl)
.apply(otionsLarge)
.error(R.drawable.image_as_cover)
.into(holder.imgLarge)
}
override fun getItemCount(): Int {
return musicList.size
}
}
| practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/adapters/AdapterViewPager.kt | 3158684326 |
package com.example.practice_musicplayer.activities
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.BitmapFactory
import android.graphics.drawable.GradientDrawable
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.audiofx.AudioEffect
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.SeekBar
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.practice_musicplayer.MainActivity
import com.example.practice_musicplayer.MusicClass
import com.example.practice_musicplayer.MusicService
import com.example.practice_musicplayer.MyService
import com.example.practice_musicplayer.R
import com.example.practice_musicplayer.databinding.ActivityMusicInterfaceBinding
import com.example.practice_musicplayer.exitApplication
import com.example.practice_musicplayer.formatDuration
import com.example.practice_musicplayer.fragments.NowPlaying
import com.example.practice_musicplayer.getImageArt
import com.example.practice_musicplayer.getMainColor
import com.example.practice_musicplayer.setSongPosition
import com.example.practice_musicplayer.utils.OnSwipeTouchListener
import com.google.android.material.snackbar.Snackbar
@Suppress("DEPRECATION")
class MusicInterface : AppCompatActivity(), ServiceConnection, MediaPlayer.OnCompletionListener {
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var binding: ActivityMusicInterfaceBinding
lateinit var musicList: ArrayList<MusicClass>
var musicService: MusicService? = null
var myService: MyService? = null
var songPosition: Int = 0
var isPlaying: Boolean = false
var isRepeating: Boolean = false
var isShuffling: Boolean = false
var counter: Int = 0
set(value) {
field = kotlin.math.max(value, 0)
}
var fIndex: Int = -1
var isLiked: Boolean = false
var min15: Boolean = false
var min30: Boolean = false
var min60: Boolean = false
var musicUrl =
"https://aydym.com/audioFiles/original/2023/10/24/17/42/944dc23f-c4cf-4267-8122-34b3eb2bada8.mp3"
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMusicInterfaceBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.interfaceSongName.isSelected = true
binding.backButton.setOnClickListener {
finish()
}
// musicList = ArrayList()
// val songList = MainActivity.songList
// musicList.add(songList[songPosition])
// val response = musicList[songPosition]
if (intent.data?.scheme.contentEquals("content")) {
val intentService = Intent(this, MusicService::class.java)
bindService(intentService, this, BIND_AUTO_CREATE)
startService(intentService)
Glide.with(this).load(MainActivity.songList!![songPosition].coverArtUrl).apply(
RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop()
).into(binding.interfaceCover)
Log.e("IF ", MainActivity.songList!![songPosition].url)
binding.interfaceSongName.text =
MainActivity.songList!![songPosition].name
binding.interfaceArtistName.text = MainActivity.songList!![songPosition].artist
} else {
Log.e("ELSE ", intent.getIntExtra("index", 0).toString())
Log.e("aglama", MainActivity.songList.toString())
initActivity()
}
binding.interfacePlay.setOnClickListener {
if (isPlaying) pauseMusic()
else playMusic()
}
binding.interfaceNext.setOnClickListener {
prevNextSong(increment = true)
}
binding.interfacePrevious.setOnClickListener {
prevNextSong(increment = false)
}
binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, isUser: Boolean) {
try {
if (isUser) {
musicService!!.mediaPlayer!!.seekTo(progress)
musicService!!.showNotification(if (isPlaying) R.drawable.pause_notification else R.drawable.play_notification)
}
} catch (e: Exception) {
return
}
}
override fun onStartTrackingTouch(p0: SeekBar?) = Unit
override fun onStopTrackingTouch(p0: SeekBar?) = Unit
})
binding.interfaceEqualizer.setOnClickListener {
try {
val eqIntent = Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL)
eqIntent.putExtra(
AudioEffect.EXTRA_AUDIO_SESSION, musicService!!.mediaPlayer!!.audioSessionId
)
eqIntent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, baseContext.packageName)
eqIntent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC)
startActivityForResult(eqIntent, 3)
} catch (e: Exception) {
Snackbar.make(
this, it, "Equalizer feature not supported in your device.", 3000
).show()
}
}
binding.interfaceCover.setOnTouchListener(object : OnSwipeTouchListener(baseContext) {
override fun onSingleClick() {
if (isPlaying) {
pauseMusic()
} else {
playMusic()
}
}
override fun onSwipeDown() {
Log.d(ContentValues.TAG, "onSwipeDown: Performed")
finish()
}
override fun onSwipeLeft() {
prevNextSong(increment = true)
}
override fun onSwipeRight() {
prevNextSong(increment = false)
}
})
binding.root.setOnTouchListener(object : OnSwipeTouchListener(baseContext) {
override fun onSwipeDown() {
Log.d(ContentValues.TAG, "onSwipeDown: Performed")
finish()
}
override fun onSwipeLeft() {
prevNextSong(increment = true)
}
override fun onSwipeRight() {
prevNextSong(increment = false)
}
})
}
private fun initActivity() {
songPosition = intent.getIntExtra("index", 0)
when (intent.getStringExtra("class")) {
"MusicAdapter" -> {
initServiceAndPlaylist(MainActivity.songList!!, shuffle = false)
}
"Now playing" -> {
showMusicInterfacePlaying()
}
"Now Playing Notification" -> {
showMusicInterfacePlaying()
}
}
}
private fun setLayout() {
try {
Glide.with(this).load(MainActivity.songList!![songPosition].coverArtUrl).apply(
RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop()
).into(binding.interfaceCover)
binding.interfaceSongName.text = MainActivity.songList!![songPosition].name
binding.interfaceArtistName.text = MainActivity.songList!![songPosition].artist
if (isRepeating) {
binding.interfaceRepeat.setImageResource(R.drawable.repeat_on)
binding.interfaceRepeat.setColorFilter(ContextCompat.getColor(this, R.color.green))
}
if (isShuffling) {
binding.interfaceShuffle.setColorFilter(ContextCompat.getColor(this, R.color.green))
binding.interfaceShuffle.setImageResource(R.drawable.shuffle_fill)
}
if (isLiked) {
NowPlaying.binding.fragmentHeartButton.setImageResource(R.drawable.heart_fill)
binding.interfaceLikeButton.setImageResource(R.drawable.heart_fill)
} else {
NowPlaying.binding.fragmentHeartButton.setImageResource(R.drawable.heart)
binding.interfaceLikeButton.setImageResource(R.drawable.heart)
}
val img = getImageArt(MainActivity.songList!![songPosition].coverArtUrl)
val image = if (img != null) {
BitmapFactory.decodeByteArray(img, 0, img.size)
} else {
BitmapFactory.decodeResource(
resources, R.drawable.image_as_cover
)
}
val bgColor = getMainColor(image)
val gradient = GradientDrawable(
GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(0xFFFFFF, bgColor)
)
binding.root.background = gradient
window?.statusBarColor = bgColor
} catch (e: Exception) {
return
}
}
private fun initSong() {
try {
if (musicService!!.mediaPlayer == null) musicService!!.mediaPlayer = MediaPlayer()
musicService!!.mediaPlayer!!.reset()
musicService!!.mediaPlayer!!.setDataSource(MainActivity.songList!![songPosition].url)
musicService!!.mediaPlayer!!.prepare()
binding.interfacePlay.setImageResource((R.drawable.pause))
binding.interfaceSeekStart.text =
formatDuration(musicService!!.mediaPlayer!!.currentPosition.toLong())
binding.interfaceSeekEnd.text =
formatDuration(musicService!!.mediaPlayer!!.duration.toLong())
binding.seekbar.progress = 0
binding.seekbar.max = musicService!!.mediaPlayer!!.duration
musicService!!.mediaPlayer!!.setOnCompletionListener(this)
playMusic()
} catch (e: Exception) {
return
}
}
fun playMusic() {
try {
musicService!!.audioManager.requestAudioFocus(
musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN
)
isPlaying = true
musicService!!.mediaPlayer!!.start()
binding.interfacePlay.setImageResource((R.drawable.pause))
musicService!!.showNotification(R.drawable.pause_notification)
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.pause_now)
} catch (e: Exception) {
return
}
}
fun pauseMusic() {
try {
musicService!!.audioManager.abandonAudioFocus(musicService)
isPlaying = false
musicService!!.mediaPlayer!!.pause()
binding.interfacePlay.setImageResource((R.drawable.play))
musicService!!.showNotification(R.drawable.play_notification)
NowPlaying.binding.fragmentButton.setImageResource(R.drawable.play_now)
} catch (e: Exception) {
return
}
}
private fun prevNextSong(increment: Boolean) {
if (increment) {
setSongPosition(increment = true)
setLayout()
initSong()
counter--
} else {
setSongPosition(increment = false)
setLayout()
initSong()
}
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
Toast.makeText(this, "connected", Toast.LENGTH_SHORT).show()
if (musicService == null) {
val binder = service as MusicService.MyBinder
musicService = binder.currentService()
musicService!!.audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
musicService!!.audioManager.requestAudioFocus(
musicService, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN
)
}
initSong()
musicService!!.seekBarHandler()
}
override fun onServiceDisconnected(p0: ComponentName?) {
musicService = null
Toast.makeText(this, "disconnected", Toast.LENGTH_SHORT).show()
}
override fun onCompletion(p0: MediaPlayer?) {
setSongPosition(increment = true)
setLayout()
initSong()
counter--
//for refreshing now playing image & text on song completion
NowPlaying.binding.fragmentTitle.isSelected = true
Glide.with(applicationContext).load(MainActivity.songList!![songPosition].url)
.apply(RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop())
.into(NowPlaying.binding.fragmentImage)
NowPlaying.binding.fragmentTitle.text = MainActivity.songList!![songPosition].name
NowPlaying.binding.fragmentAlbumName.text = MainActivity.songList!![songPosition].artist
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 3 || resultCode == RESULT_OK) return
}
override fun onDestroy() {
super.onDestroy()
if (MainActivity.songList!![songPosition].id == 0 && !isPlaying) exitApplication()
}
private fun showMusicInterfacePlaying() {
setLayout()
binding.interfaceSeekStart.text =
formatDuration(musicService!!.mediaPlayer!!.currentPosition.toLong())
binding.interfaceSeekEnd.text =
formatDuration(musicService!!.mediaPlayer!!.duration.toLong())
binding.seekbar.progress = musicService!!.mediaPlayer!!.currentPosition
binding.seekbar.max = musicService!!.mediaPlayer!!.duration
if (isPlaying) {
binding.interfacePlay.setImageResource((R.drawable.pause))
} else {
binding.interfacePlay.setImageResource((R.drawable.play))
}
}
override fun onPause() {
super.onPause()
overridePendingTransition(0, com.google.android.material.R.anim.mtrl_bottom_sheet_slide_out)
}
override fun onResume() {
super.onResume()
overridePendingTransition(com.google.android.material.R.anim.mtrl_bottom_sheet_slide_in, 0)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null) {
showMusicInterfacePlaying()
}
}
fun initServiceAndPlaylist(
playlist: ArrayList<MusicClass>, shuffle: Boolean,
) {
val intent = Intent(this, MusicService::class.java)
bindService(intent, this, BIND_AUTO_CREATE)
startService(intent)
musicList = ArrayList()
musicList.addAll(playlist)
// if (shuffle) musicList!!.shuffle()
setLayout()
}
} | practice_musicPlayer/app/src/main/java/com/example/practice_musicplayer/activities/MusicInterface.kt | 3534139419 |
package me.aquabtw.cess.listener
import me.aquabtw.cess.CESS
import me.aquabtw.cess.utils.mini
import org.bukkit.Bukkit
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
class ConnectionListener(
private val main: CESS
) : Listener {
@EventHandler
fun onJoin(event: PlayerJoinEvent) {
updateJoinMessage(event)
}
@EventHandler
fun onQuit(event: PlayerQuitEvent) {
updateQuitMessage(event)
}
private fun updateJoinMessage(event: PlayerJoinEvent) {
val player = event.player
if (!player.hasPlayedBefore()) {
val uniqueJoins = Bukkit.getOfflinePlayers().size
event.joinMessage(mini("<light_purple>+ <gray>${player.name} <dark_gray>(${uniqueJoins})"))
} else {
event.joinMessage(mini("<green>+ <gray>${player.name}"))
}
}
private fun updateQuitMessage(event: PlayerQuitEvent) {
event.quitMessage(mini("<red>- <gray>${event.player.name}"))
}
} | CESS/src/main/kotlin/me/aquabtw/cess/listener/ConnectionListener.kt | 4044288832 |
package me.aquabtw.cess.utils
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.TextDecoration
import net.kyori.adventure.text.minimessage.MiniMessage
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
private fun getResolvers(): TagResolver {
return TagResolver.resolver(
TagResolver.standard(),
Placeholder.parsed("cess", "<bold><gradient:#ffafcc:#bde0fe>CESS<reset>"),
Placeholder.parsed("dot", "<bold><dark_gray>•<reset>")
)
}
val miniMessage: MiniMessage =
MiniMessage.builder()
.tags(getResolvers())
.build()
internal fun mini(s: String): Component {
val component = miniMessage.deserialize(s)
if (!component.hasDecoration(TextDecoration.ITALIC)) {
return component.decoration(TextDecoration.ITALIC, false)
}
return component
} | CESS/src/main/kotlin/me/aquabtw/cess/utils/Adventure.kt | 1933639748 |
package me.aquabtw.cess.command
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.command.TabCompleter
abstract class CESSCommand(
val name: String
) : CommandExecutor, TabCompleter {
override fun onCommand(sender: CommandSender, command: Command, alias: String, args: Array<out String>): Boolean {
onCommand(sender, alias, args)
return true
}
override fun onTabComplete(
sender: CommandSender, command: Command, alias: String, args: Array<out String>
): List<String> {
return onTabComplete(sender, alias, args)
}
abstract fun onCommand(sender: CommandSender, alias: String, args: Array<out String>)
abstract fun onTabComplete(sender: CommandSender, alias: String, args: Array<out String>): List<String>
} | CESS/src/main/kotlin/me/aquabtw/cess/command/CESSCommand.kt | 3267842646 |
package me.aquabtw.cess.command
import me.aquabtw.cess.CESS
import me.aquabtw.cess.utils.mini
import org.bukkit.GameMode
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class GamemodeCommand(
private val main: CESS
) : CESSCommand("gmc") {
override fun onCommand(sender: CommandSender, alias: String, args: Array<out String>) {
if (sender !is Player) return
val gameMode = when (alias) {
"gmc" -> GameMode.CREATIVE
"gms" -> GameMode.SURVIVAL
"gmsp" -> GameMode.SPECTATOR
"gma" -> GameMode.ADVENTURE
else -> GameMode.SURVIVAL
}
sender.gameMode = gameMode
sender.sendMessage(mini("<cess> <dot> <green>Set your gamemode to ${gameMode.name}"))
}
override fun onTabComplete(sender: CommandSender, alias: String, args: Array<out String>): List<String> {
return emptyList()
}
} | CESS/src/main/kotlin/me/aquabtw/cess/command/GamemodeCommand.kt | 2847432204 |
package me.aquabtw.cess
import me.aquabtw.cess.command.GamemodeCommand
import me.aquabtw.cess.listener.ConnectionListener
import org.bukkit.Bukkit
import org.bukkit.plugin.java.JavaPlugin
class CESS : JavaPlugin() {
override fun onEnable() {
registerListeners()
registerCommands()
logger.info("CESS has started!")
}
private fun registerCommands() {
setOf(
GamemodeCommand(this)
).forEach {
val command = getCommand(it.name)
?: return@forEach
command.setExecutor(it)
command.tabCompleter = it
}
}
private fun registerListeners() {
setOf(
ConnectionListener(this)
).forEach {
Bukkit.getPluginManager().registerEvents(it, this)
}
}
} | CESS/src/main/kotlin/me/aquabtw/cess/CESS.kt | 3840750249 |
package me.dio.credit.application.system.entity
import jakarta.persistence.*
import me.dio.credit.application.system.enummeration.Status
import java.math.BigDecimal
import java.time.LocalDate
import java.util.UUID
@Entity
//@Table(name = "Credito")
data class Credit (
@Column(nullable = false, unique = true) val creditCode: UUID = UUID.randomUUID(),
@Column(nullable = false) val creditValue: BigDecimal = BigDecimal.ZERO,
@Column(nullable = false) val dayFirstInstallment: LocalDate,
@Column(nullable = false) val numberOfInstallments: Int = 0,
@Enumerated val status: Status = Status.IN_PROGRESS,
@ManyToOne var customer: Customer? = null,
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null)
| Desafio-Dio/src/main/kotlin/me/dio/credit/application/system/entity/Credit.kt | 2071105256 |
package me.dio.credit.application.system.entity
import jakarta.persistence.*
import java.math.BigDecimal
@Entity
//@Table(name = "Cliente")
data class Customer(
@Column(nullable = false) var firstName: String = "",
@Column(nullable = false) var lastName: String = "",
@Column(nullable = false, unique = true) var cpf: String = "",
@Column(nullable = false, unique = true) var email: String = "",
@Column(nullable = false) var income: BigDecimal = BigDecimal.ZERO,
@Column(nullable = false) var password: String = "",
@Column(nullable = false) @Embedded var address: Address = Address(),
@Column(nullable = false) @OneToMany(fetch = FetchType.LAZY,
cascade = arrayOf(CascadeType.REMOVE, CascadeType.PERSIST),
mappedBy = "customer")
var credits: List<Credit> = mutableListOf(),
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null
)
| Desafio-Dio/src/main/kotlin/me/dio/credit/application/system/entity/Customer.kt | 1089055478 |
package me.dio.credit.application.system.entity
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
@Embeddable
data class Address(
@Column(nullable = false) var zipCode: String = "",
@Column(nullable = false) var street: String = ""
)
| Desafio-Dio/src/main/kotlin/me/dio/credit/application/system/entity/Address.kt | 1728191815 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.core.app.launchActivity
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.amphibians.ui.AmphibianListFragment
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class InstrumentationTests : BaseTest() {
@Test
fun `recycler_view_content`() {
launchFragmentInContainer<AmphibianListFragment>(themeResId = R.style.Theme_Amphibians)
waitForView(withText("Great Basin Spadefoot")).check(matches(isDisplayed()))
waitForView(withText("Tiger Salamander")).check(matches(isDisplayed()))
}
@Test
fun `detail_content`() {
launchActivity<MainActivity>()
waitForView(withText("Blue Jeans Frog")).perform(click())
waitForView(withText("Blue Jeans Frog")).check(matches(isDisplayed()))
waitForView(withText("Sometimes called the Strawberry Poison-Dart Frog, this little " +
"amphibian is identifiable by its bright red body and blueish-purple arms and " +
"legs. The Blue Jeans Frog is not toxic to humans like some of its close " +
"relatives, but it can be harmful to some predators."))
.check(matches(isDisplayed()))
}
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/androidTest/java/com/example/amphibians/InstrumentationTests.kt | 1817480679 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians
import android.view.View
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.NoMatchingViewException
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import androidx.test.espresso.util.TreeIterables
import org.hamcrest.Matcher
import java.lang.Exception
import java.lang.Thread.sleep
open class BaseTest {
companion object {
fun lookFor(matcher: Matcher<View>): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isRoot()
}
override fun getDescription(): String {
return "Looking for $matcher"
}
override fun perform(uiController: UiController?, view: View?) {
var attempts = 0
val childViews: Iterable<View> = TreeIterables.breadthFirstViewTraversal(view)
childViews.forEach {
attempts++
if (matcher.matches(it)) {
return
}
}
throw NoMatchingViewException.Builder()
.withRootView(view)
.withViewMatcher(matcher)
.build()
}
}
}
}
fun waitForView(matcher: Matcher<View>,
timeoutMillis: Int = 5000,
attemptTimeoutMillis: Long = 100
): ViewInteraction {
val maxAttempts = timeoutMillis / attemptTimeoutMillis.toInt()
var attempts = 0
for (i in 0..maxAttempts) {
try {
attempts++
onView(isRoot()).perform(lookFor(matcher))
return onView(matcher)
} catch (e: Exception) {
if (attempts == maxAttempts) {
throw e
}
sleep(attemptTimeoutMillis)
}
}
throw Exception("Could not find a view matching $matcher")
}
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/androidTest/java/com/example/amphibians/BaseTest.kt | 2273097844 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.amphibians.databinding.FragmentAmphibianDetailBinding
/**
* This Fragment shows the detailed information on a particular Amphibian
*/
class AmphibianDetailFragment : Fragment() {
private val viewModel: AmphibianViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentAmphibianDetailBinding.inflate(inflater)
binding.lifecycleOwner = this
binding.viewModel = viewModel
// Inflate the layout for this fragment
return binding.root
}
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianDetailFragment.kt | 444233151 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.amphibians.network.Amphibian
import com.example.amphibians.network.AmphibianApi
import com.example.amphibians.network.AmphibianApiService
import kotlinx.coroutines.launch
enum class AmphibianApiStatus {LOADING, ERROR, DONE}
class AmphibianViewModel : ViewModel() {
private val _status = MutableLiveData<AmphibianApiStatus>()
val status: LiveData<AmphibianApiStatus> = _status
// Create properties to represent MutableLiveData and LiveData for a single amphibian object.
// This will be used to display the details of an amphibian when a list item is clicked
private val _amphibians = MutableLiveData<List<Amphibian>>()
val amphibians: LiveData<List<Amphibian>> = _amphibians
private val _amphibian = MutableLiveData<Amphibian>()
val amphibian: LiveData<Amphibian> = _amphibian
init {
getAmphibianList()
}
private fun getAmphibianList() {
viewModelScope.launch {
_status.value = AmphibianApiStatus.LOADING
try {
_amphibians.value = AmphibianApi.retrofitService.getAmphibians()
_status.value = AmphibianApiStatus.DONE
} catch (e: Exception) {
_status.value = AmphibianApiStatus.ERROR
_amphibians.value = emptyList()
}
}
}
fun onAmphibianClicked(amphibian: Amphibian) {
// Set the amphibian object
_amphibian.value= amphibian
}
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianViewModel.kt | 1548828569 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.example.amphibians.R
import com.example.amphibians.databinding.FragmentAmphibianListBinding
class AmphibianListFragment : Fragment() {
private val viewModel: AmphibianViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentAmphibianListBinding.inflate(inflater)
// TODO: call the view model method that calls the amphibians app
binding.lifecycleOwner = this
binding.viewModel = viewModel
binding.recyclerView.adapter = AmphibianListAdapter(AmphibianListener { amphibian ->
viewModel.onAmphibianClicked(amphibian)
findNavController()
.navigate(R.id.action_amphibianListFragment_to_amphibianDetailFragment)
})
// Inflate the layout for this fragment
return binding.root
}
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianListFragment.kt | 1661950255 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.amphibians.databinding.ListViewItemBinding
import com.example.amphibians.network.Amphibian
/**
* This class implements a [RecyclerView] [ListAdapter] which uses Data Binding to present [List]
* data, including computing diffs between lists.
*/
class AmphibianListAdapter(val clickListener: AmphibianListener) :
ListAdapter<Amphibian, AmphibianListAdapter.AmphibianViewHolder>(DiffCallback) {
class AmphibianViewHolder(
var binding: ListViewItemBinding
) : RecyclerView.ViewHolder(binding.root){
fun bind(clickListener: AmphibianListener, amphibian: Amphibian) {
binding.amphibian = amphibian
binding.clickListener = clickListener
binding.executePendingBindings()
}
}
companion object DiffCallback : DiffUtil.ItemCallback<Amphibian>() {
override fun areItemsTheSame(oldItem: Amphibian, newItem: Amphibian): Boolean {
return oldItem.name == newItem.name
}
override fun areContentsTheSame(oldItem: Amphibian, newItem: Amphibian): Boolean {
return oldItem.type == newItem.type && oldItem.description == newItem.description
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AmphibianViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return AmphibianViewHolder(
ListViewItemBinding.inflate(layoutInflater, parent, false)
)
}
override fun onBindViewHolder(holder: AmphibianViewHolder, position: Int) {
val amphibian = getItem(position)
holder.bind(clickListener, amphibian)
}
}
class AmphibianListener(val clickListener: (amphibian: Amphibian) -> Unit) {
fun onClick(amphibian: Amphibian) = clickListener(amphibian)
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/ui/AmphibianListAdapter.kt | 1932573560 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI.setupActionBarWithNavController
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
setupActionBarWithNavController(this, navController)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/MainActivity.kt | 3623787225 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians
import android.view.View
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.amphibians.network.Amphibian
import com.example.amphibians.ui.AmphibianApiStatus
import com.example.amphibians.ui.AmphibianListAdapter
/**
* Updates the data shown in the [RecyclerView]
*/
@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<Amphibian>?) {
val adapter = recyclerView.adapter as AmphibianListAdapter
adapter.submitList(data)
}
/**
* This binding adapter displays the [AmphibianApiStatus] of the network request in an image view.
* When the request is loading, it displays a loading_animation. If the request has an error, it
* displays a broken image to reflect the connection error. When the request is finished, it
* hides the image view.
*/
@BindingAdapter("apiStatus")
fun bindStatus(statusImageView: ImageView, status: AmphibianApiStatus?) {
when(status) {
AmphibianApiStatus.LOADING -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.loading_animation)
}
AmphibianApiStatus.DONE -> {
statusImageView.visibility = View.GONE
}
AmphibianApiStatus.ERROR -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.ic_connection_error)
}
}
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/BindingAdapters.kt | 2455731843 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians.network
import com.squareup.moshi.Json
/**
* This data class defines an Amphibian which includes the amphibian's name, the type of
* amphibian, and a brief description of the amphibian.
* The property names of this data class are used by Moshi to match the names of values in JSON.
*/
data class Amphibian(
val name: String,
val type: String,
val description: String
)
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/network/Amphibian.kt | 3993332077 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.amphibians.network
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
// Create a property for the base URL provided in the codelab- done
private const val BASE_URL = "https://developer.android.com/courses/pathways/android-basics-kotlin-unit-4-pathway-2/"
// Build the Moshi object with Kotlin adapter factory that Retrofit will be using to parse JSON-done
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
// Build a Retrofit object with the Moshi converter-done
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
interface AmphibianApiService {
// Declare a suspended function to get the list of amphibians
@GET("android-basics-kotlin-unit-4-pathway-2-project-api.json")
suspend fun getAmphibians(): List<Amphibian>
}
// Create an object that provides a lazy-initialized retrofit service-done
object AmphibianApi {
val retrofitService: AmphibianApiService by lazy { retrofit.create(AmphibianApiService::class.java) }
}
| csm3123-lab6/Lab6_AmphibianApp-master/app/src/main/java/com/example/amphibians/network/AmphibianApiService.kt | 1098614865 |
fun main() {
var count = 0
for (i in 1..50) {
Thread {
count += 1
println("Thread: $i count: $count")
}.start()
}
}
| csm3123-lab6/lab6_coroutines-main/threadcount.kt | 1028030537 |
import kotlinx.coroutines.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
val formatter = DateTimeFormatter.ISO_LOCAL_TIME
val time = { formatter.format(LocalDateTime.now()) }
suspend fun getValue(): Double {
println("entering getValue() at ${time()}")
delay(3000)
println("leaving getValue() at ${time()}")
return Math.random()
}
fun main() {
runBlocking {
val num1 = getValue()
val num2 = getValue()
println("result of num1 + num2 is ${num1 + num2}")
}
}
| csm3123-lab6/lab6_coroutines-main/coroutine2.kt | 2095651887 |
import kotlinx.coroutines.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
val formatter = DateTimeFormatter.ISO_LOCAL_TIME
val time = { formatter.format(LocalDateTime.now()) }
suspend fun getValue(): Double {
println("entering getValue() at ${time()}")
delay(3000)
println("leaving getValue() at ${time()}")
return Math.random()
}
fun main() {
runBlocking {
val num1 = async { getValue() }
val num2 = async { getValue() }
println("result of num1 + num2 is ${num1.await() + num2.await()}")
}
}
| csm3123-lab6/lab6_coroutines-main/coroutine2a.kt | 621519227 |
import kotlinx.coroutines.*
fun main() {
val states = arrayOf("Starting", "Doing Task 1", "Doing Task 2", "Ending")
repeat(3) {
GlobalScope.launch { //use coroutines instead of thread
println("${Thread.currentThread()} has started")
for (i in states) {
println("${Thread.currentThread()} - $i")
}
}
}
}
| csm3123-lab6/lab6_coroutines-main/practiceExercise.kt | 3462655626 |
fun main() {
val states = arrayOf("Starting", "Doing Task 1", "Doing Task 2", "Ending")
repeat(3) {
Thread {
println("${Thread.currentThread()} has started")
for (i in states) {
println("${Thread.currentThread()} - $i")
Thread.sleep(50) //sleep for 50ms
}
}.start()
}
}
| csm3123-lab6/lab6_coroutines-main/multiplethread.kt | 1902275933 |
fun main() {
val thread = Thread {
println("${Thread.currentThread()} has run.")
}
thread.start()
}
| csm3123-lab6/lab6_coroutines-main/thread.kt | 3726304761 |
import kotlinx.coroutines.*
fun main() {
repeat(3) {
GlobalScope.launch {
println("Hi from ${Thread.currentThread()}")
}
}
}
| csm3123-lab6/lab6_coroutines-main/coroutine1.kt | 173352602 |
package com.example.debugging
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.debugging", appContext.packageName)
}
} | csm3123-lab6/Lab6_Debugging-master/app/src/androidTest/java/com/example/debugging/ExampleInstrumentedTest.kt | 866264895 |
package com.example.debugging
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)
}
} | csm3123-lab6/Lab6_Debugging-master/app/src/test/java/com/example/debugging/ExampleUnitTest.kt | 4266698688 |
package com.example.debugging
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
public val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
division()
}
fun division() {
val numerator = 60
var denominator = 4
repeat(4) {
Log.v(TAG, "${numerator / denominator}")
denominator--
}
}
} | csm3123-lab6/Lab6_Debugging-master/app/src/main/java/com/example/debugging/MainActivity.kt | 599676396 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
* MainActivity sets the content view activity_main, a fragment container that contains
* overviewFragment.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/MainActivity.kt | 892584274 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos
import android.view.View
import android.widget.ImageView
import androidx.core.net.toUri
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.example.android.marsphotos.network.MarsPhoto
import com.example.android.marsphotos.overview.MarsApiStatus
import com.example.android.marsphotos.overview.PhotoGridAdapter
/**
* Updates the data shown in the [RecyclerView].
*/
@BindingAdapter("listData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<MarsPhoto>?) {
val adapter = recyclerView.adapter as PhotoGridAdapter
adapter.submitList(data)
}
/**
* Uses the Coil library to load an image by URL into an [ImageView]
*/
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
imgUrl?.let {
val imgUri = imgUrl.toUri().buildUpon().scheme("https").build()
imgView.load(imgUri) {
placeholder(R.drawable.loading_animation)
error(R.drawable.ic_broken_image)
}
}
}
/**
* This binding adapter displays the [MarsApiStatus] of the network request in an image view. When
* the request is loading, it displays a loading_animation. If the request has an error, it
* displays a broken image to reflect the connection error. When the request is finished, it
* hides the image view.
*/
@BindingAdapter("marsApiStatus")
fun bindStatus(statusImageView: ImageView, status: MarsApiStatus) {
when (status) {
MarsApiStatus.LOADING -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.loading_animation)
}
MarsApiStatus.ERROR -> {
statusImageView.visibility = View.VISIBLE
statusImageView.setImageResource(R.drawable.ic_connection_error)
}
MarsApiStatus.DONE -> {
statusImageView.visibility = View.GONE
}
}
}
| csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/BindingAdapters.kt | 1813625294 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos.network
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
private const val BASE_URL = "https://android-kotlin-fun-mars-server.appspot.com/"
/**
* Build the Moshi object that Retrofit will be using, making sure to add the Kotlin adapter for
* full Kotlin compatibility.
*/
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
/**
* Use the Retrofit builder to build a retrofit object using a Moshi converter with our Moshi
* object.
*/
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
/**
* A public interface that exposes the [getPhotos] method
*/
interface MarsApiService {
/**
* Returns a [List] of [MarsPhoto] and this method can be called from a Coroutine.
* The @GET annotation indicates that the "photos" endpoint will be requested with the GET
* HTTP method
*/
@GET("photos")
suspend fun getPhotos(): List<MarsPhoto>
}
/**
* A public Api object that exposes the lazy-initialized Retrofit service
*/
object MarsApi {
val retrofitService: MarsApiService by lazy { retrofit.create(MarsApiService::class.java) }
}
| csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/network/MarsApiService.kt | 4201349311 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos.network
import com.squareup.moshi.Json
/**
* This data class defines a Mars photo which includes an ID, and the image URL.
* The property names of this data class are used by Moshi to match the names of values in JSON.
*/
data class MarsPhoto(
val id: String,
// used to map img_src from the JSON to imgSrcUrl in our class
@Json(name = "img_src") val imgSrcUrl: String
) | csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/network/MarsPhoto.kt | 3722717877 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos.overview
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.android.marsphotos.databinding.FragmentOverviewBinding
/**
* This fragment shows the the status of the Mars photos web services transaction.
*/
class OverviewFragment : Fragment() {
private val viewModel: OverviewViewModel by viewModels()
/**
* Inflates the layout with Data Binding, sets its lifecycle owner to the OverviewFragment
* to enable Data Binding to observe LiveData, and sets up the RecyclerView with an adapter.
*/
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentOverviewBinding.inflate(inflater)
// Allows Data Binding to Observe LiveData with the lifecycle of this Fragment
binding.lifecycleOwner = this
// Giving the binding access to the OverviewViewModel
binding.viewModel = viewModel
// Sets the adapter of the photosGrid RecyclerView
binding.photosGrid.adapter = PhotoGridAdapter()
return binding.root
}
}
| csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewFragment.kt | 89015591 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos.overview
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.marsphotos.databinding.GridViewItemBinding
import com.example.android.marsphotos.network.MarsPhoto
/**
* This class implements a [RecyclerView] [ListAdapter] which uses Data Binding to present [List]
* data, including computing diffs between lists.
*/
class PhotoGridAdapter :
ListAdapter<MarsPhoto, PhotoGridAdapter.MarsPhotosViewHolder>(DiffCallback) {
/**
* The MarsPhotosViewHolder constructor takes the binding variable from the associated
* GridViewItem, which nicely gives it access to the full [MarsPhoto] information.
*/
class MarsPhotosViewHolder(
private var binding: GridViewItemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(marsPhoto: MarsPhoto) {
binding.photo = marsPhoto
// This is important, because it forces the data binding to execute immediately,
// which allows the RecyclerView to make the correct view size measurements
binding.executePendingBindings()
}
}
/**
* Allows the RecyclerView to determine which items have changed when the [List] of
* [MarsPhoto] has been updated.
*/
companion object DiffCallback : DiffUtil.ItemCallback<MarsPhoto>() {
override fun areItemsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean {
return oldItem.imgSrcUrl == newItem.imgSrcUrl
}
}
/**
* Create new [RecyclerView] item views (invoked by the layout manager)
*/
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): MarsPhotosViewHolder {
return MarsPhotosViewHolder(
GridViewItemBinding.inflate(LayoutInflater.from(parent.context))
)
}
/**
* Replaces the contents of a view (invoked by the layout manager)
*/
override fun onBindViewHolder(holder: MarsPhotosViewHolder, position: Int) {
val marsPhoto = getItem(position)
holder.bind(marsPhoto)
}
}
| csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/overview/PhotoGridAdapter.kt | 2297339626 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos.overview
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android.marsphotos.network.MarsApi
import com.example.android.marsphotos.network.MarsPhoto
import kotlinx.coroutines.launch
enum class MarsApiStatus { LOADING, ERROR, DONE }
/**
* The [ViewModel] that is attached to the [OverviewFragment].
*/
class OverviewViewModel : ViewModel() {
// The internal MutableLiveData that stores the status of the most recent request
private val _status = MutableLiveData<MarsApiStatus>()
// The external immutable LiveData for the request status
val status: LiveData<MarsApiStatus> = _status
// Internally, we use a MutableLiveData, because we will be updating the List of MarsPhoto
// with new values
private val _photos = MutableLiveData<List<MarsPhoto>>()
// The external LiveData interface to the property is immutable, so only this class can modify
val photos: LiveData<List<MarsPhoto>> = _photos
/**
* Call getMarsPhotos() on init so we can display status immediately.
*/
init {
getMarsPhotos()
}
/**
* Gets Mars photos information from the Mars API Retrofit service and updates the
* [MarsPhoto] [List] [LiveData].
*/
private fun getMarsPhotos() {
viewModelScope.launch {
_status.value = MarsApiStatus.LOADING
try {
_photos.value = MarsApi.retrofitService.getPhotos()
_status.value = MarsApiStatus.DONE
} catch (e: Exception) {
_status.value = MarsApiStatus.ERROR
_photos.value = listOf()
}
}
}
}
| csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewViewModel.kt | 236331125 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
* MainActivity sets the content view activity_main, a fragment container that contains
* overviewFragment.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/MainActivity.kt | 892584274 |
package com.example.android.marsphotos.network
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
private const val BASE_URL =
"https://android-kotlin-fun-mars-server.appspot.com"
/**
* Build the Moshi object with Kotlin adapter factory that Retrofit will be using.
*/
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
/**
* The Retrofit object with the Moshi converter.
*/
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
/**
* A public interface that exposes the [getPhotos] method
*/
interface MarsApiService {
/**
* Returns a [List] of [MarsPhoto] and this method can be called from a Coroutine.
* The @GET annotation indicates that the "photos" endpoint will be requested with the GET
* HTTP method
*/
@GET("photos")
suspend fun getPhotos() : List<MarsPhoto>
}
/**
* A public Api object that exposes the lazy-initialized Retrofit service
*/
object MarsApi {
val retrofitService: MarsApiService by lazy { retrofit.create(MarsApiService::class.java) }
} | csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/network/MarsApiService.kt | 3765231990 |
package com.example.android.marsphotos.network
import com.squareup.moshi.Json
/**
* This data class defines a Mars photo which includes an ID, and the image URL.
* The property names of this data class are used by Moshi to match the names of values in JSON.
*/
data class MarsPhoto(
val id: String,
@Json(name = "img_src") val imgSrcUrl: String
) | csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/network/MarsPhoto.kt | 4026924341 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos.overview
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.android.marsphotos.databinding.FragmentOverviewBinding
/**
* This fragment shows the the status of the Mars photos web services transaction.
*/
class OverviewFragment : Fragment() {
private val viewModel: OverviewViewModel by viewModels()
/**
* Inflates the layout with Data Binding, sets its lifecycle owner to the OverviewFragment
* to enable Data Binding to observe LiveData, and sets up the RecyclerView with an adapter.
*/
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentOverviewBinding.inflate(inflater)
// Allows Data Binding to Observe LiveData with the lifecycle of this Fragment
binding.lifecycleOwner = this
// Giving the binding access to the OverviewViewModel
binding.viewModel = viewModel
return binding.root
}
}
| csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewFragment.kt | 3155813697 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* 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.example.android.marsphotos.overview
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android.marsphotos.network.MarsApi
import kotlinx.coroutines.launch
/**
* The [ViewModel] that is attached to the [OverviewFragment].
*/
class OverviewViewModel : ViewModel() {
// The internal MutableLiveData that stores the status of the most recent request
private val _status = MutableLiveData<String>()
// The external immutable LiveData for the request status
val status: LiveData<String> = _status
/**
* Call getMarsPhotos() on init so we can display status immediately.
*/
init {
getMarsPhotos()
}
/**
* Gets Mars photos information from the Mars API Retrofit service and updates the
* [MarsPhoto] [List] [LiveData].
*/
private fun getMarsPhotos() {
viewModelScope.launch {
try {
val listResult = MarsApi.retrofitService.getPhotos()
_status.value = "Success: ${listResult.size} Mars photos retrieved"
} catch (e: Exception) {
_status.value = "Failure: ${e.message}"
}
}
}
}
| csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewViewModel.kt | 3910161745 |
package com.example.learnmvp
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.learnmvp", appContext.packageName)
}
} | Add-User/app/src/androidTest/java/com/example/learnmvp/ExampleInstrumentedTest.kt | 764863305 |
package com.example.learnmvp
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.learnmvp.view.alluser.MainActivity
import com.example.learnmvp.view.random.RandomImageActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@get:Rule
val mainActivity = ActivityScenarioRule(MainActivity::class.java)
@Test
fun testGotoRandomPage() {
onView(withId(R.id.randomImage)).perform(click())
onView(withId(R.id.randomImageLayout)).check(matches(isDisplayed()))
}
} | Add-User/app/src/androidTest/java/com/example/learnmvp/MainActivityTest.kt | 4288106713 |
package com.example.learnmvp
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)
}
} | Add-User/app/src/test/java/com/example/learnmvp/ExampleUnitTest.kt | 2745523028 |
package com.example.learnmvp
import com.example.learnmvp.data.local.dao.UserDao
import com.example.learnmvp.data.local.entity.UserEntity
import com.example.learnmvp.data.local.repository.UserRepository
import com.example.learnmvp.data.local.repository.UserRepositoryImpl
import com.example.learnmvp.data.remote.repository.RemoteRepository
import com.example.learnmvp.view.alluser.MainPresenter
import com.example.learnmvp.view.alluser.MainView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class MainPresenterTest {
@Mock
private lateinit var view : MainView.AllUserView
private lateinit var presenter: MainPresenter
lateinit var userDao: UserDao
private lateinit var repository: UserRepositoryImpl
@Before
fun setup(){
userDao = mock(UserDao::class.java)
repository = UserRepositoryImpl(userDao)
presenter = MainPresenter(view, repository)
}
@Test
fun `Test Get User`() = runTest {
val listUser = listOf(UserEntity("jhoan", "[email protected]"), UserEntity("herlina", "panjaitan"))
`when`(
userDao.getAllUsers()
).thenReturn(listUser)
val result = repository.getUsers()
assertEquals(listUser, result)
}
} | Add-User/app/src/test/java/com/example/learnmvp/MainPresenterTest.kt | 1984383859 |
package com.example.learnmvp.di
import android.content.Context
import com.example.learnmvp.data.local.dabase.UserDatabase
import com.example.learnmvp.data.local.dao.UserDao
import com.example.learnmvp.data.local.repository.UserRepository
import com.example.learnmvp.data.local.repository.UserRepositoryImpl
import com.example.learnmvp.data.remote.repository.RemoteRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class CacheModule {
@Provides
@Singleton
fun provideUserDatabase (@ApplicationContext context: Context) : UserDatabase {
return UserDatabase.getDatabase(context)
}
@Provides
@Singleton
fun provideDao(userDatabase: UserDatabase) : UserDao {
return userDatabase.userDao()
}
@Provides
@Singleton
fun provideRepository(userDao: UserDao) : UserRepository {
return UserRepositoryImpl(userDao)
}
} | Add-User/app/src/main/java/com/example/learnmvp/di/CacheModule.kt | 568039503 |
package com.example.learnmvp.di
import com.example.learnmvp.data.remote.apiservice.ApiService
import com.example.learnmvp.data.remote.repository.RemoteRepository
import com.example.learnmvp.data.remote.repository.RemoteRepositoryImpl
import com.google.gson.Gson
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
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
val BASE_URL = "https://dog.ceo/api/"
@Provides
@Singleton
fun provideHttpClient() : OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
}
@Provides
@Singleton
fun provideRetrofit(
httpClient: OkHttpClient
) : Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
fun provideApiService(retrofit: Retrofit) : ApiService {
return retrofit.create(ApiService::class.java)
}
@Provides
@Singleton
fun providerRepository(
apiService: ApiService
) : RemoteRepository {
return RemoteRepositoryImpl(apiService)
}
} | Add-User/app/src/main/java/com/example/learnmvp/di/NetworkModule.kt | 1590235882 |
package com.example.learnmvp.model
data class DataModel(
var name: String,
val id: String,
) | Add-User/app/src/main/java/com/example/learnmvp/model/DataModel.kt | 3738654821 |
package com.example.learnmvp.view.alluser
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.learnmvp.data.local.dabase.UserDatabase
import com.example.learnmvp.data.local.entity.UserEntity
import com.example.learnmvp.data.local.repository.UserRepository
import com.example.learnmvp.data.local.repository.UserRepositoryImpl
import com.example.learnmvp.databinding.ActivityMainBinding
import com.example.learnmvp.view.formuser.FormUserActivity
import com.example.learnmvp.view.random.RandomImageActivity
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity(), MainView.AllUserView {
lateinit var presenter: MainView.Presenter
lateinit var binding: ActivityMainBinding
lateinit var userAdapter: MainAdapter
@Inject
lateinit var userRepository: UserRepository
lateinit var result: ActivityResultLauncher<Intent>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initView()
bindPresenter()
}
private fun initView(){
result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if(result.resultCode == 123) {
println("yes, it return 123")
presenter.loadDataUser()
}
}
presenter = MainPresenter(this, userRepository)
presenter.loadDataUser()
userAdapter = MainAdapter(object: MainAdapter.MainListener{
})
presenter.loadDataUser()
}
private fun bindPresenter() {
binding.btnChangeData.setOnClickListener {
presenter.goToInsertForm()
}
binding.randomImage.setOnClickListener {
startActivity(Intent(this, RandomImageActivity::class.java))
}
}
override fun showListUser(users: List<UserEntity>) {
binding.rvUsers.apply {
adapter = userAdapter
layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.VERTICAL, false)
itemAnimator = null
}
userAdapter.updateUser(users)
}
override fun goToInsertPage() {
val intent = Intent(this, FormUserActivity::class.java)
result.launch(intent)
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainActivity.kt | 2865997308 |
package com.example.learnmvp.view.alluser
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.learnmvp.data.local.entity.UserEntity
import com.example.learnmvp.databinding.ItemUserBinding
class MainAdapter (private val listener : MainListener) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
private var listUser = mutableListOf<UserEntity>()
fun updateUser(listUser: List<UserEntity>) {
this.listUser = listUser as MutableList<UserEntity>
notifyDataSetChanged()
}
class ViewHolder (private val binding: ItemUserBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(user: UserEntity){
binding.tvId.text = user.id.toString()
binding.tvName.text = user.name
binding.tvEmail.text = user.email
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = ItemUserBinding.inflate(inflater, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return listUser.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(listUser[position])
holder.itemView.setOnLongClickListener{
toggleSelection(position)
true
}
}
private fun toggleSelection(position: Int) {
}
interface MainListener {
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainAdapter.kt | 1217464005 |
package com.example.learnmvp.view.alluser
import com.example.learnmvp.data.local.repository.UserRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
class MainPresenter @Inject constructor(
private val allUserView: MainView.AllUserView,
private val userRepository: UserRepository
) : MainView.Presenter {
override fun loadDataUser() {
CoroutineScope(Dispatchers.IO).launch {
try {
val data = userRepository.getUsers()
withContext(Dispatchers.Main) {
allUserView.showListUser(data)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}
}
override fun goToInsertForm() {
allUserView.goToInsertPage()
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainPresenter.kt | 2267364769 |
package com.example.learnmvp.view.alluser
import com.example.learnmvp.data.local.entity.UserEntity
interface MainView {
interface AllUserView {
fun showListUser(users: List<UserEntity>)
fun goToInsertPage()
}
interface Presenter {
fun loadDataUser()
fun goToInsertForm()
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainView.kt | 364955085 |
package com.example.learnmvp.view.random
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.bumptech.glide.Glide
import com.example.learnmvp.data.remote.model.ApiResponse
import com.example.learnmvp.data.remote.repository.RemoteRepository
import com.example.learnmvp.databinding.ActivityRandomImageBinding
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class RandomImageActivity : AppCompatActivity(), RandomImage.RandomImageView {
lateinit var binding : ActivityRandomImageBinding
lateinit var presenter: RandomImage.Presenter
@Inject
lateinit var remoteRepository: RemoteRepository
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRandomImageBinding.inflate(layoutInflater)
setContentView(binding.root)
initView()
}
private fun initView() {
presenter = RandomImagePresenter(remoteRepository, this)
presenter.loadImage()
}
override fun showImage(response: ApiResponse?) {
Glide.with(this)
.load(response?.message)
.into(binding.imgRandom)
}
override fun failedLoadImage() {
Toast.makeText(this, "Failed To Load Image", Toast.LENGTH_SHORT).show()
}
override fun showLoading(b: Boolean) {
if(b){
binding.pbItem.visibility = View.VISIBLE
} else
binding.pbItem.visibility = View.GONE
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/random/RandomImageActivity.kt | 3090430885 |
package com.example.learnmvp.view.random
import com.example.learnmvp.data.remote.repository.NetworkResult
import com.example.learnmvp.data.remote.repository.RemoteRepository
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import javax.inject.Inject
class RandomImagePresenter @Inject constructor(
private val remoteRepository: RemoteRepository,
private val view: RandomImage.RandomImageView
) : RandomImage.Presenter {
override fun loadImage() {
view.showLoading(true)
CoroutineScope(Dispatchers.IO).launch {
remoteRepository.getRandom().collect{ result ->
when(result){
is NetworkResult.ErrorResponse -> {
withContext(Dispatchers.Main){
view.showLoading(false)
view.failedLoadImage()
}
}
is NetworkResult.Success -> {
withContext(Dispatchers.Main){
view.showLoading(false)
view.showImage(result.data)
}
}
}
}
}
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/random/RandomImagePresenter.kt | 1888162378 |
package com.example.learnmvp.view.random
import com.example.learnmvp.data.remote.model.ApiResponse
interface RandomImage {
interface RandomImageView {
fun showImage(response: ApiResponse?)
fun failedLoadImage()
fun showLoading(b: Boolean)
}
interface Presenter {
fun loadImage()
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/random/RandomImage.kt | 1987085915 |
package com.example.learnmvp.view.formuser
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ActionMenuView
import android.widget.Toast
import com.example.learnmvp.R
import com.example.learnmvp.data.local.dabase.UserDatabase
import com.example.learnmvp.data.local.dao.UserDao
import com.example.learnmvp.data.local.entity.UserEntity
import com.example.learnmvp.data.local.repository.UserRepository
import com.example.learnmvp.data.local.repository.UserRepositoryImpl
import com.example.learnmvp.databinding.ActivityFormUserBinding
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class FormUserActivity : AppCompatActivity(), FormUser.UserView {
lateinit var formUserPresenter: FormUserPresenter
lateinit var binding: ActivityFormUserBinding
@Inject
lateinit var userRepository: UserRepository
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFormUserBinding.inflate(layoutInflater)
setContentView(binding.root)
initView()
initFields()
initPresenter()
}
private fun initView() {
formUserPresenter = FormUserPresenter(this, userRepository)
}
private fun initFields() {
binding.btnInputUser.setOnClickListener {
formUserPresenter.createUser(binding.name.text.toString(), binding.email.text.toString())
}
}
private fun initPresenter() {
}
override fun showError() {
}
override fun showLoading() {
}
override fun successAddUser() {
Toast.makeText(this, "Success Add User", Toast.LENGTH_SHORT).show()
setResult(123)
finish()
}
override fun failedAddUser() {
Toast.makeText(this, "Failed Add User", Toast.LENGTH_SHORT).show()
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/formuser/FormUserActivity.kt | 1227636264 |
package com.example.learnmvp.view.formuser
import com.example.learnmvp.data.local.entity.UserEntity
import com.example.learnmvp.data.local.repository.UserRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class FormUserPresenter(
private val view: FormUser.UserView,
private val repository: UserRepository
) : FormUser.UserPresenter {
override fun insertUser(user: UserEntity) {
CoroutineScope(Dispatchers.IO)
.launch {
try {
repository.insertUser(user)
withContext(Dispatchers.Main) {
view.successAddUser()
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
withContext(Dispatchers.Main) {
view.failedAddUser()
}
}
}
}
fun createUser(name: String, email: String) {
val user = UserEntity(name, email)
CoroutineScope(Dispatchers.IO)
.launch {
try {
repository.insertUser(user)
withContext(Dispatchers.Main) {
view.successAddUser()
}
} catch (e: Exception) {
e.printStackTrace()
view.failedAddUser()
}
}
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/formuser/FormUserPresenter.kt | 214739608 |
package com.example.learnmvp.view.formuser
import com.example.learnmvp.data.local.entity.UserEntity
interface FormUser {
interface UserView {
fun showError()
fun showLoading()
fun successAddUser()
fun failedAddUser()
}
interface UserPresenter {
fun insertUser(user: UserEntity)
}
} | Add-User/app/src/main/java/com/example/learnmvp/view/formuser/FormUser.kt | 3089522410 |
package com.example.learnmvp.data.local.repository
import com.example.learnmvp.data.local.dao.UserDao
import com.example.learnmvp.data.local.entity.UserEntity
interface UserRepository {
suspend fun getUsers() : List<UserEntity>
suspend fun insertUser(user: UserEntity)
suspend fun deleteUser(id: String)
} | Add-User/app/src/main/java/com/example/learnmvp/data/local/repository/UserRepository.kt | 1515593274 |
package com.example.learnmvp.data.local.repository
import com.example.learnmvp.data.local.dao.UserDao
import com.example.learnmvp.data.local.entity.UserEntity
import javax.inject.Inject
class UserRepositoryImpl @Inject constructor(private val userDao: UserDao) : UserRepository {
override suspend fun getUsers(): List<UserEntity> {
return userDao.getAllUsers()
}
override suspend fun insertUser(user: UserEntity) {
return userDao.insertUser(user)
}
override suspend fun deleteUser(id: String) {
return userDao.deleteUser(id)
}
} | Add-User/app/src/main/java/com/example/learnmvp/data/local/repository/UserRepositoryImpl.kt | 3994149812 |
package com.example.learnmvp.data.local.dabase
import android.content.Context
import android.service.autofill.UserData
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.learnmvp.data.local.dao.UserDao
import com.example.learnmvp.data.local.entity.UserEntity
@Database(entities = [UserEntity::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase(){
abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE : UserDatabase? = null
fun getDatabase(context: Context): UserDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"my_app_database"
).build()
INSTANCE = instance
instance
}
}
}
} | Add-User/app/src/main/java/com/example/learnmvp/data/local/dabase/UserDatabase.kt | 2787128254 |
package com.example.learnmvp.data.local.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "users")
data class UserEntity(
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "email") val email: String,
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id: Int = 0
} | Add-User/app/src/main/java/com/example/learnmvp/data/local/entity/UserEntity.kt | 704647921 |
package com.example.learnmvp.data.local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.example.learnmvp.data.local.entity.UserEntity
@Dao
interface UserDao {
@Query("SELECT * FROM users")
suspend fun getAllUsers() : List<UserEntity>
@Insert
suspend fun insertUser(user: UserEntity)
@Query("DELETE FROM users WHERE id = :userId")
suspend fun deleteUser(userId: String)
} | Add-User/app/src/main/java/com/example/learnmvp/data/local/dao/UserDao.kt | 846030611 |
package com.example.learnmvp.data.remote.repository
import android.view.KeyEvent.DispatcherState
import com.example.learnmvp.data.remote.apiservice.ApiService
import com.example.learnmvp.data.remote.model.ApiResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import javax.inject.Inject
class RemoteRepositoryImpl @Inject constructor(private val apiService: ApiService) : RemoteRepository {
override fun getRandom(): Flow<NetworkResult<ApiResponse>> {
return flow {
try {
val response = apiService.getRandomDog()
if(response.isSuccessful) {
emit(NetworkResult.Success<ApiResponse>(response.body()))
} else{
emit(NetworkResult.ErrorResponse("Failed get Image"))
}
}catch (e: java.lang.Exception){
throw e
}
}.catch { e ->
emit(NetworkResult.ErrorResponse(e.message.orEmpty()))
}.flowOn(Dispatchers.IO)
}
} | Add-User/app/src/main/java/com/example/learnmvp/data/remote/repository/RemoteRepositoryImpl.kt | 1143363867 |
package com.example.learnmvp.data.remote.repository
import com.example.learnmvp.data.remote.model.ApiResponse
sealed class NetworkResult<out T> {
class Success<out T>(val data : ApiResponse? = null) : NetworkResult<T>()
class ErrorResponse(val message: String ?= null): NetworkResult<Nothing>()
} | Add-User/app/src/main/java/com/example/learnmvp/data/remote/repository/NetworkResult.kt | 2509548164 |
package com.example.learnmvp.data.remote.repository
import com.example.learnmvp.data.remote.model.ApiResponse
import kotlinx.coroutines.flow.Flow
interface RemoteRepository{
fun getRandom() : Flow<NetworkResult<ApiResponse>>
} | Add-User/app/src/main/java/com/example/learnmvp/data/remote/repository/RemoteRepository.kt | 1294940396 |
package com.example.learnmvp.data.remote.model
import com.google.gson.annotations.SerializedName
data class ApiResponse (
@SerializedName("message")
val message: String,
@SerializedName("status")
val success: String,
) | Add-User/app/src/main/java/com/example/learnmvp/data/remote/model/ApiResponse.kt | 3319207011 |
package com.example.learnmvp.data.remote.apiservice
import com.example.learnmvp.data.remote.model.ApiResponse
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Url
interface ApiService {
@GET("breeds/image/random")
suspend fun getRandomDog() : Response<ApiResponse>
} | Add-User/app/src/main/java/com/example/learnmvp/data/remote/apiservice/ApiService.kt | 1683242684 |
package com.example.learnmvp
import android.app.Activity
import android.app.Application
import android.os.Bundle
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class LearnApplication : Application(), Application.ActivityLifecycleCallbacks{
override fun onActivityCreated(p0: Activity, p1: Bundle?) {
println(" on activity crated")
}
override fun onActivityStarted(p0: Activity) {
println("on activity started")
}
override fun onActivityResumed(p0: Activity) {
println("on activityResumed")
}
override fun onActivityPaused(p0: Activity) {
println("on activity paused")
}
override fun onActivityStopped(p0: Activity) {
println("on activity stopped")
}
override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
println("on activity saveInstance")
}
override fun onActivityDestroyed(p0: Activity) {
println("on activity destroyed")
}
} | Add-User/app/src/main/java/com/example/learnmvp/LearnApplication.kt | 4042645640 |
package com.samueljuma.upcomingmovies
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.samueljuma.upcomingmovies", appContext.packageName)
}
} | Upcoming-Movies/app/src/androidTest/java/com/samueljuma/upcomingmovies/ExampleInstrumentedTest.kt | 1743107209 |
package com.samueljuma.upcomingmovies
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)
}
} | Upcoming-Movies/app/src/test/java/com/samueljuma/upcomingmovies/ExampleUnitTest.kt | 857797672 |
package com.samueljuma.upcomingmovies
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
} | Upcoming-Movies/app/src/main/java/com/samueljuma/upcomingmovies/MainActivity.kt | 2714411482 |
package com.example.mviapp
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.mviapp", appContext.packageName)
}
} | Android-Architectures/MVIApp/app/src/androidTest/java/com/example/mviapp/ExampleInstrumentedTest.kt | 2121896536 |
package com.example.mviapp
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)
}
} | Android-Architectures/MVIApp/app/src/test/java/com/example/mviapp/ExampleUnitTest.kt | 2961496136 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.