content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package dev.rushia.mynoteapps.helper import android.app.Application import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import dev.rushia.mynoteapps.ui.insert.NoteAddUpdateViewModel import dev.rushia.mynoteapps.ui.main.MainViewModel class ViewModelFactory private constructor(private val mApplication: Application) : ViewModelProvider.NewInstanceFactory() { companion object { @Volatile private var INSTANCE: ViewModelFactory? = null @JvmStatic fun getInstance(application: Application): ViewModelFactory { if (INSTANCE == null) { synchronized(ViewModelFactory::class.java) { INSTANCE = ViewModelFactory(application) } } return INSTANCE as ViewModelFactory } } @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) { return MainViewModel(mApplication) as T } else if (modelClass.isAssignableFrom(NoteAddUpdateViewModel::class.java)) { return NoteAddUpdateViewModel(mApplication) as T } throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}") } }
fundamental-android-practice/MyNoteApps/app/src/main/java/dev/rushia/mynoteapps/helper/ViewModelFactory.kt
1782837153
package dev.rushia.mynoteapps.helper import androidx.recyclerview.widget.DiffUtil import dev.rushia.mynoteapps.database.Note class NoteDiffCallback(private val oldNoteList: List<Note>, private val newNoteList: List<Note>) : DiffUtil.Callback() { override fun getOldListSize(): Int { return oldNoteList.size } override fun getNewListSize(): Int { return newNoteList.size } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldNoteList[oldItemPosition].id == newNoteList[newItemPosition].id } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldNote = oldNoteList[oldItemPosition] val newNote = newNoteList[newItemPosition] return oldNote.title == newNote.title && oldNote.description == newNote.description } }
fundamental-android-practice/MyNoteApps/app/src/main/java/dev/rushia/mynoteapps/helper/NoteDiffCallback.kt
1546652882
package dev.rushia.mynoteapps.helper import java.text.SimpleDateFormat import java.util.Date import java.util.Locale object DateHelper { fun getCurrentDate(): String { val dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()) val date = Date() return dateFormat.format(date) } }
fundamental-android-practice/MyNoteApps/app/src/main/java/dev/rushia/mynoteapps/helper/DateHelper.kt
42834041
package dev.rushia.mybackgroundthread import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mybackgroundthread", appContext.packageName) } }
fundamental-android-practice/MyBackgroundThread/app/src/androidTest/java/dev/rushia/mybackgroundthread/ExampleInstrumentedTest.kt
383441271
package dev.rushia.mybackgroundthread 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) } }
fundamental-android-practice/MyBackgroundThread/app/src/test/java/dev/rushia/mybackgroundthread/ExampleUnitTest.kt
1696237577
package dev.rushia.mybackgroundthread import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper import android.widget.Button import android.widget.TextView import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.concurrent.Executors class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btnStart = findViewById<Button>(R.id.btn_start) val tvStatus = findViewById<TextView>(R.id.tv_status) val executor = Executors.newSingleThreadExecutor() val handler = Handler(Looper.getMainLooper()) btnStart.setOnClickListener { lifecycleScope.launch(Dispatchers.Default) { //simulate process in background thread for (i in 0..10) { delay(500) val percentage = i * 10 withContext(Dispatchers.Main) { //update ui in main thread if (percentage == 100) { tvStatus.setText(R.string.task_completed) } else {kfd tvStatus.text = String.format(getString(R.string.compressing), percentage) } } } } } } }
fundamental-android-practice/MyBackgroundThread/app/src/main/java/dev/rushia/mybackgroundthread/MainActivity.kt
623494146
package dev.rushia.mysharedpreferences import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mysharedpreferences", appContext.packageName) } }
fundamental-android-practice/MySharedPreferences/app/src/androidTest/java/dev/rushia/mysharedpreferences/ExampleInstrumentedTest.kt
810940271
package dev.rushia.mysharedpreferences 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) } }
fundamental-android-practice/MySharedPreferences/app/src/test/java/dev/rushia/mysharedpreferences/ExampleUnitTest.kt
3112403792
package dev.rushia.mysharedpreferences import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import dev.rushia.mysharedpreferences.databinding.ActivityMainBinding class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var mUserPreference: UserPreference private lateinit var binding: ActivityMainBinding private var isPreferenceEmpty = false private lateinit var userModel: UserModel private val resultLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result: ActivityResult -> /* Akan dipanggil ketika FormUserPreferenceActivity ditutup */ if (result.data != null && result.resultCode == FormUserPreferenceActivity.RESULT_CODE) { userModel = result.data?.getParcelableExtra<UserModel>(FormUserPreferenceActivity.EXTRA_RESULT) as UserModel populateView(userModel) checkForm(userModel) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) supportActionBar?.title = "My User Preference" mUserPreference = UserPreference(this) showExistingPreference() binding.btnSave.setOnClickListener(this) } /* Menampilkan preference yang ada */ private fun showExistingPreference() { userModel = mUserPreference.getUser() populateView(userModel) checkForm(userModel) } /* Set tampilan menggunakan preferences */ private fun populateView(userModel: UserModel) { binding.tvName.text = if (userModel.name.toString().isEmpty()) "Tidak Ada" else userModel.name binding.tvAge.text = if (userModel.age.toString().isEmpty()) "Tidak Ada" else userModel.age.toString() binding.tvIsLoveMu.text = if (userModel.isLove) "Ya" else "Tidak" binding.tvEmail.text = if (userModel.email.toString().isEmpty()) "Tidak Ada" else userModel.email binding.tvPhone.text = if (userModel.phone.toString().isEmpty()) "Tidak Ada" else userModel.phone } private fun checkForm(userModel: UserModel) { when { userModel.name.toString().isNotEmpty() -> { binding.btnSave.text = getString(R.string.change) isPreferenceEmpty = false } else -> { binding.btnSave.text = getString(R.string.save) isPreferenceEmpty = true } } } override fun onClick(view: View) { if (view.id == R.id.btn_save) { val intent = Intent(this@MainActivity, FormUserPreferenceActivity::class.java) when { isPreferenceEmpty -> { intent.putExtra( FormUserPreferenceActivity.EXTRA_TYPE_FORM, FormUserPreferenceActivity.TYPE_ADD ) intent.putExtra("USER", userModel) } else -> { intent.putExtra( FormUserPreferenceActivity.EXTRA_TYPE_FORM, FormUserPreferenceActivity.TYPE_EDIT ) intent.putExtra("USER", userModel) } } resultLauncher.launch(intent) } } }
fundamental-android-practice/MySharedPreferences/app/src/main/java/dev/rushia/mysharedpreferences/MainActivity.kt
4046431645
package dev.rushia.mysharedpreferences import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.view.MenuItem import android.view.View import android.widget.Toast import dev.rushia.mysharedpreferences.databinding.ActivityFormUserPreferenceBinding class FormUserPreferenceActivity : AppCompatActivity(), View.OnClickListener { private lateinit var binding: ActivityFormUserPreferenceBinding companion object { const val EXTRA_TYPE_FORM = "extra_type_form" const val EXTRA_RESULT = "extra_result" const val RESULT_CODE = 101 const val TYPE_ADD = 1 const val TYPE_EDIT = 2 private const val FIELD_REQUIRED = "Field tidak boleh kosong" private const val FIELD_DIGIT_ONLY = "Hanya boleh terisi numerik" private const val FIELD_IS_NOT_VALID = "Email tidak valid" } private lateinit var userModel: UserModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityFormUserPreferenceBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnSave.setOnClickListener(this) userModel = intent.getParcelableExtra<UserModel>("USER") as UserModel val formType = intent.getIntExtra(EXTRA_TYPE_FORM, 0) var actionBarTitle = "" var btnTitle = "" when (formType) { TYPE_ADD -> { actionBarTitle = "Tambah Baru" btnTitle = "Simpan" } TYPE_EDIT -> { actionBarTitle = "Ubah" btnTitle = "Update" showPreferenceInForm() } } supportActionBar?.title = actionBarTitle supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.btnSave.text = btnTitle } private fun showPreferenceInForm() { binding.edtName.setText(userModel.name) binding.edtEmail.setText(userModel.email) binding.edtAge.setText(userModel.age.toString()) binding.edtPhone.setText(userModel.phone) if (userModel.isLove) { binding.rbYes.isChecked = true } else { binding.rbNo.isChecked = true } } override fun onClick(view: View) { if (view.id == R.id.btn_save) { val name = binding.edtName.text.toString().trim() val email = binding.edtEmail.text.toString().trim() val age = binding.edtAge.text.toString().trim() val phoneNo = binding.edtPhone.text.toString().trim() val isLoveMU = binding.rgLoveMu.checkedRadioButtonId == R.id.rb_yes if (name.isEmpty()) { binding.edtName.error = FIELD_REQUIRED return } if (email.isEmpty()) { binding.edtEmail.error = FIELD_REQUIRED return } if (!isValidEmail(email)) { binding.edtEmail.error = FIELD_IS_NOT_VALID return } if (age.isEmpty()) { binding.edtAge.error = FIELD_REQUIRED return } if (phoneNo.isEmpty()) { binding.edtPhone.error = FIELD_REQUIRED return } if (!TextUtils.isDigitsOnly(phoneNo)) { binding.edtPhone.error = FIELD_DIGIT_ONLY return } saveUser(name, email, age, phoneNo, isLoveMU) val resultIntent = Intent() resultIntent.putExtra(EXTRA_RESULT, userModel) setResult(RESULT_CODE, resultIntent) finish() } } /* Save data ke dalam preferences */ private fun saveUser(name: String, email: String, age: String, phoneNo: String, isLoveMU: Boolean) { val userPreference = UserPreference(this) userModel.name = name userModel.email = email userModel.age = Integer.parseInt(age) userModel.phone = phoneNo userModel.isLove = isLoveMU userPreference.setUser(userModel) Toast.makeText(this, "Data tersimpan", Toast.LENGTH_SHORT).show() } /** * Cek apakah emailnya valid * * @param email inputan email * @return true jika email valid */ private fun isValidEmail(email: CharSequence): Boolean { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } }
fundamental-android-practice/MySharedPreferences/app/src/main/java/dev/rushia/mysharedpreferences/FormUserPreferenceActivity.kt
915608164
package dev.rushia.mysharedpreferences import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class UserModel( var name: String? = null, var email: String? = null, var age: Int = 0, var phone: String? = null, var isLove: Boolean = false ) : Parcelable
fundamental-android-practice/MySharedPreferences/app/src/main/java/dev/rushia/mysharedpreferences/UserModel.kt
1929269000
package dev.rushia.mysharedpreferences import android.content.Context internal class UserPreference(context: Context) { private val preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) fun setUser(value: UserModel) { val editor = preferences.edit() editor.putString(NAME, value.name) editor.putString(EMAIL, value.email) editor.putInt(AGE, value.age) editor.putString(PHONE_NUMBER, value.phone) editor.putBoolean(LOVE_MU, value.isLove) editor.apply() } fun getUser(): UserModel { val model = UserModel() model.name = preferences.getString(NAME, "") model.email = preferences.getString(EMAIL, "") model.age = preferences.getInt(AGE, 0) model.phone = preferences.getString(PHONE_NUMBER, "") model.isLove = preferences.getBoolean(LOVE_MU, false) return model } companion object { private const val PREFS_NAME = "user_pref" private const val NAME = "name" private const val EMAIL = "email" private const val AGE = "age" private const val PHONE_NUMBER = "phone" private const val LOVE_MU = "islove" } }
fundamental-android-practice/MySharedPreferences/app/src/main/java/dev/rushia/mysharedpreferences/UserPreference.kt
200893505
package dev.rushia.myviewmodel import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.myviewmodel", appContext.packageName) } }
fundamental-android-practice/MyViewModel/app/src/androidTest/java/dev/rushia/myviewmodel/ExampleInstrumentedTest.kt
3889801300
package dev.rushia.myviewmodel 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) } }
fundamental-android-practice/MyViewModel/app/src/test/java/dev/rushia/myviewmodel/ExampleUnitTest.kt
3864806172
package dev.rushia.myviewmodel import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { var result = 0 fun calculate(width: String, height: String, length: String) { result = width.toInt() * height.toInt() * length.toInt() } }
fundamental-android-practice/MyViewModel/app/src/main/java/dev/rushia/myviewmodel/MainViewModel.kt
2995738249
package dev.rushia.myviewmodel import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import androidx.lifecycle.ViewModelProvider import dev.rushia.myviewmodel.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var activityMainBinding: ActivityMainBinding // private lateinit var viewModel: MainViewModel private val viewModel: MainViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityMainBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(activityMainBinding.root) // viewModel = ViewModelProvider(this).get(MainViewModel::class.java) displayResult() activityMainBinding.btnCalculate.setOnClickListener { val width = activityMainBinding.edtWidth.text.toString() val height = activityMainBinding.edtHeight.text.toString() val length = activityMainBinding.edtLength.text.toString() when { width.isEmpty() -> { activityMainBinding.edtWidth.error = "Masih kosong" } height.isEmpty() -> { activityMainBinding.edtHeight.error = "Masih kosong" } length.isEmpty() -> { activityMainBinding.edtLength.error = "Masih kosong" } else -> { viewModel.calculate(width, height, length) displayResult() } } } } private fun displayResult() { activityMainBinding.tvResult.text = viewModel.result.toString() } }
fundamental-android-practice/MyViewModel/app/src/main/java/dev/rushia/myviewmodel/MainActivity.kt
371251246
package dev.rushia.myreadwritefile import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.myreadwritefile", appContext.packageName) } }
fundamental-android-practice/MyReadWriteFile/app/src/androidTest/java/dev/rushia/myreadwritefile/ExampleInstrumentedTest.kt
2112693687
package dev.rushia.myreadwritefile 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) } }
fundamental-android-practice/MyReadWriteFile/app/src/test/java/dev/rushia/myreadwritefile/ExampleUnitTest.kt
1298711612
package dev.rushia.myreadwritefile import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog import dev.rushia.myreadwritefile.databinding.ActivityMainBinding class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.buttonNew.setOnClickListener(this) binding.buttonOpen.setOnClickListener(this) binding.buttonSave.setOnClickListener(this) } override fun onClick(v: View?) { when (v?.id) { R.id.button_new -> newFile() R.id.button_open -> showList() R.id.button_save -> saveFile() } } private fun newFile() { binding.editFile.setText("") binding.editTitle.setText("") Toast.makeText(this, "Clearing File", Toast.LENGTH_SHORT).show() } private fun showList() { val items = fileList() val builder = AlertDialog.Builder(this) builder.setTitle("Pilih File yang diinginkan") builder.setItems(items) { _, item -> loadData(items[item].toString()) } val alert = builder.create() alert.show() } private fun loadData(title: String) { val fileModel = FileHelper.readFromFile(this, title) binding.editTitle.setText(fileModel.filename) binding.editFile.setText(fileModel.data) Toast.makeText(this, "Loading " + fileModel.filename + " data", Toast.LENGTH_SHORT).show() } private fun saveFile() { when { binding.editTitle.text.toString().isEmpty() -> Toast.makeText( this, "Title harus diisi terlebih dahulu", Toast.LENGTH_SHORT ).show() binding.editFile.text.toString().isEmpty() -> Toast.makeText( this, "Kontent harus diisi terlebih dahulu", Toast.LENGTH_SHORT ).show() else -> { val title = binding.editTitle.text.toString() val text = binding.editFile.text.toString() val fileModel = FileModel() fileModel.filename = title fileModel.data = text FileHelper.writeToFile(fileModel, this) Toast.makeText(this, "Saving " + fileModel.filename + " file", Toast.LENGTH_SHORT) .show() } } } }
fundamental-android-practice/MyReadWriteFile/app/src/main/java/dev/rushia/myreadwritefile/MainActivity.kt
2813877400
package dev.rushia.myreadwritefile import android.content.Context internal object FileHelper { fun writeToFile(fileModel: FileModel, context: Context) { context.openFileOutput(fileModel.filename, Context.MODE_PRIVATE).use { it.write(fileModel.data?.toByteArray()) } } fun readFromFile(context: Context, filename: String): FileModel { val fileModel = FileModel() fileModel.filename = filename fileModel.data = context.openFileInput(filename).bufferedReader().useLines { lines -> lines.fold("") { some, text -> "$some$text\n" } } return fileModel } }
fundamental-android-practice/MyReadWriteFile/app/src/main/java/dev/rushia/myreadwritefile/FileHelper.kt
2197957805
package dev.rushia.myreadwritefile data class FileModel( var filename: String? = null, var data: String? = null )
fundamental-android-practice/MyReadWriteFile/app/src/main/java/dev/rushia/myreadwritefile/FileModel.kt
2247035930
package dev.rushia.mybroadcastreceiver import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mybroadcastreceiver", appContext.packageName) } }
fundamental-android-practice/MyBroadcastReceiver/app/src/androidTest/java/dev/rushia/mybroadcastreceiver/ExampleInstrumentedTest.kt
2047712967
package dev.rushia.mybroadcastreceiver 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) } }
fundamental-android-practice/MyBroadcastReceiver/app/src/test/java/dev/rushia/mybroadcastreceiver/ExampleUnitTest.kt
112089632
package dev.rushia.mybroadcastreceiver import android.Manifest import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.View import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import com.google.android.material.snackbar.Snackbar import dev.rushia.mybroadcastreceiver.databinding.ActivityMainBinding class MainActivity : AppCompatActivity(), View.OnClickListener { companion object { const val ACTION_DOWNLOAD_STATUS = "download_status" } private var binding: ActivityMainBinding? = null var requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { Toast.makeText(this, "Sms receiver permission diterima", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Sms receiver permission ditolak", Toast.LENGTH_SHORT).show() } } private lateinit var downloadReceiver: BroadcastReceiver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding?.root) binding?.btnPermission?.setOnClickListener(this) binding?.btnDownload?.setOnClickListener(this) downloadReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Snackbar.make(findViewById(android.R.id.content), "Download Selesai", Snackbar.LENGTH_SHORT).show() } } val downloadIntentFilter = IntentFilter(ACTION_DOWNLOAD_STATUS) registerReceiver(downloadReceiver, downloadIntentFilter) } override fun onClick(v: View?) { when (v?.id) { R.id.btn_permission -> requestPermissionLauncher.launch(Manifest.permission.RECEIVE_SMS) R.id.btn_download -> { Handler(Looper.getMainLooper()).postDelayed( { val notifyFinishIntent = Intent().setAction(ACTION_DOWNLOAD_STATUS) sendBroadcast(notifyFinishIntent) }, 3000 ) } } } override fun onDestroy() { super.onDestroy() unregisterReceiver(downloadReceiver) binding = null } }
fundamental-android-practice/MyBroadcastReceiver/app/src/main/java/dev/rushia/mybroadcastreceiver/MainActivity.kt
3879994751
package dev.rushia.mybroadcastreceiver import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import dev.rushia.mybroadcastreceiver.databinding.ActivitySmsReceiverBinding class SmsReceiverActivity : AppCompatActivity(){ companion object { const val EXTRA_SMS_NO = "extra_sms_no" const val EXTRA_SMS_MESSAGE = "extra_sms_message" } private var binding: ActivitySmsReceiverBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySmsReceiverBinding.inflate(layoutInflater) setContentView(binding?.root) title = getString(R.string.incoming_message) binding?.btnClose?.setOnClickListener { finish() } val senderNo = intent.getStringExtra(EXTRA_SMS_NO) val senderMessage = intent.getStringExtra(EXTRA_SMS_MESSAGE) binding?.tvFrom?.text = getString(R.string.from, senderNo) binding?.tvMessage?.text = senderMessage } override fun onDestroy() { super.onDestroy() binding = null } }
fundamental-android-practice/MyBroadcastReceiver/app/src/main/java/dev/rushia/mybroadcastreceiver/SmsReceiverActivity.kt
638113255
package dev.rushia.mybroadcastreceiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.provider.Telephony import android.util.Log class SmsReceiver : BroadcastReceiver() { companion object { private val TAG = SmsReceiver::class.java.simpleName } override fun onReceive(context: Context, intent: Intent) { // This method is called when the BroadcastReceiver is receiving an Intent broadcast. if (intent.action == Telephony.Sms.Intents.SMS_RECEIVED_ACTION) { val messages = Telephony.Sms.Intents.getMessagesFromIntent(intent) for (message in messages) { val senderNum = message.originatingAddress val body = message.messageBody Log.d(TAG, "senderNum: $senderNum; message: $message") val showSmsIntent = Intent(context, SmsReceiverActivity::class.java) showSmsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK showSmsIntent.putExtra(SmsReceiverActivity.EXTRA_SMS_NO, senderNum) showSmsIntent.putExtra(SmsReceiverActivity.EXTRA_SMS_MESSAGE, body) context.startActivity(showSmsIntent) } } } }
fundamental-android-practice/MyBroadcastReceiver/app/src/main/java/dev/rushia/mybroadcastreceiver/SmsReceiver.kt
387561764
package dev.rushia.mylivedata import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mylivedata", appContext.packageName) } }
fundamental-android-practice/MyLiveData/app/src/androidTest/java/dev/rushia/mylivedata/ExampleInstrumentedTest.kt
4101037215
package dev.rushia.mylivedata 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) } }
fundamental-android-practice/MyLiveData/app/src/test/java/dev/rushia/mylivedata/ExampleUnitTest.kt
1994908482
package dev.rushia.mylivedata import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.SystemClock import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import dev.rushia.mylivedata.databinding.ActivityMainBinding import java.util.Timer import java.util.TimerTask class MainActivity : AppCompatActivity() { private lateinit var liveDataTimerViewModel: MainViewModel private lateinit var activityMainBinding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityMainBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(activityMainBinding.root) liveDataTimerViewModel = ViewModelProvider(this)[MainViewModel::class.java] subscribe() } private fun subscribe(){ val elapsedTimeObserver = Observer<Long?>{aLong -> val newText = [email protected](R.string.seconds, aLong) activityMainBinding.timerTextview.text = newText } liveDataTimerViewModel.getElapsedTime().observe(this, elapsedTimeObserver) } } class MainViewModel : ViewModel() { companion object { private const val ONE_SECOND = 1000 } private val mInitialTime = SystemClock.elapsedRealtime() private val mElapsedTime = MutableLiveData<Long?>() init { val timer = Timer() timer.scheduleAtFixedRate(object : TimerTask() { override fun run() { val newValue = (SystemClock.elapsedRealtime() - mInitialTime) / 1000 mElapsedTime.postValue(newValue) } }, ONE_SECOND.toLong(), ONE_SECOND.toLong()) } fun getElapsedTime(): LiveData<Long?>{ return mElapsedTime } }
fundamental-android-practice/MyLiveData/app/src/main/java/dev/rushia/mylivedata/MainActivity.kt
2036091571
package dev.rushia.mynavigationdrawer import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mynavigationdrawer", appContext.packageName) } }
fundamental-android-practice/MyNavigationDrawer/app/src/androidTest/java/dev/rushia/mynavigationdrawer/ExampleInstrumentedTest.kt
2108088418
package dev.rushia.mynavigationdrawer 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) } }
fundamental-android-practice/MyNavigationDrawer/app/src/test/java/dev/rushia/mynavigationdrawer/ExampleUnitTest.kt
1692433850
package dev.rushia.mynavigationdrawer.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is home Fragment" } val text: LiveData<String> = _text }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/ui/home/HomeViewModel.kt
3168768465
package dev.rushia.mynavigationdrawer.ui.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dev.rushia.mynavigationdrawer.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java) _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textHome homeViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/ui/home/HomeFragment.kt
3563591411
package dev.rushia.mynavigationdrawer.ui.gallery import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class GalleryViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is gallery Fragment" } val text: LiveData<String> = _text }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/ui/gallery/GalleryViewModel.kt
1251030147
package dev.rushia.mynavigationdrawer.ui.gallery import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dev.rushia.mynavigationdrawer.databinding.FragmentGalleryBinding class GalleryFragment : Fragment() { private var _binding: FragmentGalleryBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val galleryViewModel = ViewModelProvider(this).get(GalleryViewModel::class.java) _binding = FragmentGalleryBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textGallery galleryViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/ui/gallery/GalleryFragment.kt
50165538
package dev.rushia.mynavigationdrawer.ui.slideshow import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SlideshowViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is slideshow Fragment" } val text: LiveData<String> = _text }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/ui/slideshow/SlideshowViewModel.kt
1311172654
package dev.rushia.mynavigationdrawer.ui.slideshow import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import dev.rushia.mynavigationdrawer.databinding.FragmentSlideshowBinding class SlideshowFragment : Fragment() { private var _binding: FragmentSlideshowBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val slideshowViewModel = ViewModelProvider(this).get(SlideshowViewModel::class.java) _binding = FragmentSlideshowBinding.inflate(inflater, container, false) val root: View = binding.root val textView: TextView = binding.textSlideshow slideshowViewModel.text.observe(viewLifecycleOwner) { textView.text = it } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/ui/slideshow/SlideshowFragment.kt
2573911816
package dev.rushia.mynavigationdrawer import android.os.Bundle import android.view.Menu import android.widget.TextView import com.google.android.material.snackbar.Snackbar import com.google.android.material.navigation.NavigationView import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import de.hdodenhof.circleimageview.CircleImageView import dev.rushia.mynavigationdrawer.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding private lateinit var profileCircleImageView: CircleImageView private var profileImageUrl = "https://media.discordapp.net/attachments/891712323717333008/1211029784608505916/WhatsApp_Image_2024-02-25_at_2.19.22_AM.jpeg?ex=65ecb660&is=65da4160&hm=2c2a5985aef9adf0083e241915f1bb98f23808b041914751405e17a3098cf384&=&format=webp&width=350&height=350" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.appBarMain.toolbar) binding.appBarMain.fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = binding.drawerLayout val navView: NavigationView = binding.navView profileCircleImageView = navView.getHeaderView(0).findViewById(R.id.imageView) Glide.with(this).load(profileImageUrl).into(profileCircleImageView) navView.getHeaderView(0).findViewById<TextView>(R.id.tv_nav_header_title).text = "Fathan Maulana" navView.getHeaderView(0).findViewById<TextView>(R.id.tv_nav_header_email).text = "[email protected]" val navController = findNavController(R.id.nav_host_fragment_content_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_cart ), drawerLayout ) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/MainActivity.kt
705591761
package dev.rushia.mynavigationdrawer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class SubwayActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_subway) } }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/SubwayActivity.kt
911758631
package dev.rushia.mynavigationdrawer import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [CartFragment.newInstance] factory method to * create an instance of this fragment. */ class CartFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_cart, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment CartFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = CartFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
fundamental-android-practice/MyNavigationDrawer/app/src/main/java/dev/rushia/mynavigationdrawer/CartFragment.kt
2849623529
package dev.rushia.myflexiblefragment import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.myflexiblefragment", appContext.packageName) } }
fundamental-android-practice/MyFlexibleFragment/app/src/androidTest/java/dev/rushia/myflexiblefragment/ExampleInstrumentedTest.kt
3198266661
package dev.rushia.myflexiblefragment 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) } }
fundamental-android-practice/MyFlexibleFragment/app/src/test/java/dev/rushia/myflexiblefragment/ExampleUnitTest.kt
3066401471
package dev.rushia.myflexiblefragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.commit // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [CategoryFragment.newInstance] factory method to * create an instance of this fragment. */ class CategoryFragment : Fragment(), View.OnClickListener { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_category, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment CategoryFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = CategoryFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val btnDetailCategory: Button = view.findViewById(R.id.btn_detail_category) btnDetailCategory.setOnClickListener(this) } override fun onClick(v: View?) { if (v?.id == R.id.btn_detail_category) { val detailCategoryFragment = DetailCategoryFragment() val bundle = Bundle() bundle.putString(DetailCategoryFragment.EXTRA_NAME, "Lifestyle") val description = "Kategori ini akan berisi produk-produk lifestyle" detailCategoryFragment.arguments = bundle detailCategoryFragment.description = description val fragmentManager = parentFragmentManager fragmentManager.commit { addToBackStack(null) replace(R.id.frame_container, detailCategoryFragment, DetailCategoryFragment::class.java.simpleName) } } } }
fundamental-android-practice/MyFlexibleFragment/app/src/main/java/dev/rushia/myflexiblefragment/CategoryFragment.kt
1369889522
package dev.rushia.myflexiblefragment import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.fragment.app.commit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val fragmentManager = supportFragmentManager val homeFragment = HomeFragment() val fragment = fragmentManager.findFragmentByTag(HomeFragment::class.java.simpleName) if(fragment !is HomeFragment){ Log.d("MyFlexibleFragment", "Fragment Name :"+HomeFragment::class.java.simpleName) fragmentManager.commit { add(R.id.frame_container, homeFragment, HomeFragment::class.java.simpleName) } } } }
fundamental-android-practice/MyFlexibleFragment/app/src/main/java/dev/rushia/myflexiblefragment/MainActivity.kt
2483603657
package dev.rushia.myflexiblefragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [DetailCategoryFragment.newInstance] factory method to * create an instance of this fragment. */ class DetailCategoryFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null var description: String? = null private lateinit var tvCategoryName: TextView private lateinit var tvCategoryDescription: TextView private lateinit var btnProfile: Button private lateinit var btnShowDialog: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_detail_category, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) tvCategoryName = view.findViewById(R.id.tv_category_name) tvCategoryDescription = view.findViewById(R.id.tv_category_description) btnProfile = view.findViewById(R.id.btn_profile) btnShowDialog = view.findViewById(R.id.btn_show_dialog) if (savedInstanceState != null){ val descFromBundle = savedInstanceState.getString(EXTRA_DESCRIPTION) description = descFromBundle } if (arguments != null){ val categoryName = arguments?.getString(EXTRA_NAME) tvCategoryName.text = categoryName tvCategoryDescription.text = description } } companion object { var EXTRA_NAME = "extra_name" var EXTRA_DESCRIPTION = "extra_description" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment DetailCategoryFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = DetailCategoryFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
fundamental-android-practice/MyFlexibleFragment/app/src/main/java/dev/rushia/myflexiblefragment/DetailCategoryFragment.kt
343187861
package dev.rushia.myflexiblefragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.commit // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [HomeFragment.newInstance] factory method to * create an instance of this fragment. */ class HomeFragment : Fragment(), View.OnClickListener { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_home, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment HomeFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = HomeFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val btnCategory: Button = view.findViewById(R.id.btn_category) btnCategory.setOnClickListener(this) } override fun onClick(v: View?) { if (v?.id == R.id.btn_category) { val categoryFragment = CategoryFragment() val fragmentManager = parentFragmentManager fragmentManager.commit { addToBackStack(null) replace( R.id.frame_container, categoryFragment, CategoryFragment::class.java.simpleName ) } } } }
fundamental-android-practice/MyFlexibleFragment/app/src/main/java/dev/rushia/myflexiblefragment/HomeFragment.kt
318741111
package dev.rushia.myunittest import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.myunittest", appContext.packageName) } }
fundamental-android-practice/MyUnitTest/app/src/androidTest/java/dev/rushia/myunittest/ExampleInstrumentedTest.kt
2810863037
package dev.rushia.myunittest 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) } }
fundamental-android-practice/MyUnitTest/app/src/test/java/dev/rushia/myunittest/ExampleUnitTest.kt
1553815527
package dev.rushia.myunittest import org.junit.Assert.* import org.junit.Test import org.mockito.Mockito.mock import org.junit.Before class MainViewModelTest { private lateinit var mainViewModel: MainViewModel private lateinit var cuboidModel: CuboidModel private val dummyLength = 12.0 private val dummyWidth = 7.0 private val dummyHeight = 6.0 private val dummyVolume = 504.0 @Before fun before() { cuboidModel = mock(CuboidModel::class.java) mainViewModel = MainViewModel(cuboidModel) } @Test fun getCircumference() { } @Test fun getSurfaceArea() { } @Test fun getVolume() { cuboidModel = CuboidModel() mainViewModel = MainViewModel(cuboidModel) mainViewModel.save(dummyWidth, dummyLength, dummyHeight) val volume = mainViewModel.getVolume() assertEquals(dummyVolume, volume, 0.0001) } @Test fun save() { } }
fundamental-android-practice/MyUnitTest/app/src/test/java/dev/rushia/myunittest/MainViewModelTest.kt
1261108024
package dev.rushia.myunittest class MainViewModel(private val cuboidModel: CuboidModel) { fun getCircumference() = cuboidModel.getCircumference() fun getSurfaceArea() = cuboidModel.getSurfaceArea() fun getVolume() = cuboidModel.getVolume() fun save(w: Double, l: Double, h: Double) { cuboidModel.save(w, l, h) } }
fundamental-android-practice/MyUnitTest/app/src/main/java/dev/rushia/myunittest/MainViewModel.kt
3952615335
package dev.rushia.myunittest import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.view.View import dev.rushia.myunittest.databinding.ActivityMainBinding class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var activityMainBinding: ActivityMainBinding private lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityMainBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(activityMainBinding.root) mainViewModel = MainViewModel(CuboidModel()) activityMainBinding.btnSave.setOnClickListener(this) activityMainBinding.btnCalculateSurfaceArea.setOnClickListener(this) activityMainBinding.btnCalculateCircumference.setOnClickListener(this) activityMainBinding.btnCalculateVolume.setOnClickListener(this) } override fun onClick(v: View?) { val length = activityMainBinding.edtLength.text.toString().trim() val width = activityMainBinding.edtWidth.text.toString().trim() val height = activityMainBinding.edtHeight.text.toString().trim() when { TextUtils.isEmpty(length) -> { activityMainBinding.edtLength.error = "Field ini tidak boleh kosong" } TextUtils.isEmpty(width) -> { activityMainBinding.edtWidth.error = "Field ini tidak boleh kosong" } TextUtils.isEmpty(height) -> { activityMainBinding.edtHeight.error = "Field ini tidak boleh kosong" } else -> { val valueLength = length.toDouble() val valueWidth = width.toDouble() val valueHeight = height.toDouble() when (v?.id) { R.id.btn_save -> { mainViewModel.save(valueLength, valueWidth, valueHeight) visible() } R.id.btn_calculate_circumference -> { activityMainBinding.tvResult.text = mainViewModel.getCircumference().toString() gone() } R.id.btn_calculate_surface_area -> { activityMainBinding.tvResult.text = mainViewModel.getSurfaceArea().toString() gone() } R.id.btn_calculate_volume -> { activityMainBinding.tvResult.text = mainViewModel.getVolume().toString() gone() } } } } } private fun visible() { activityMainBinding.btnCalculateVolume.visibility = View.VISIBLE activityMainBinding.btnCalculateCircumference.visibility = View.VISIBLE activityMainBinding.btnCalculateSurfaceArea.visibility = View.VISIBLE activityMainBinding.btnSave.visibility = View.GONE } private fun gone() { activityMainBinding.btnCalculateVolume.visibility = View.GONE activityMainBinding.btnCalculateCircumference.visibility = View.GONE activityMainBinding.btnCalculateSurfaceArea.visibility = View.GONE activityMainBinding.btnSave.visibility = View.VISIBLE } }
fundamental-android-practice/MyUnitTest/app/src/main/java/dev/rushia/myunittest/MainActivity.kt
4107511558
package dev.rushia.myunittest class CuboidModel { private var width = 0.0 private var length = 0.0 private var height = 0.0 fun getVolume(): Double = width * length * height fun getSurfaceArea(): Double { val wl = width * length val wh = width * height val lh = length * height return 2 * (wl + wh + lh) } fun getCircumference(): Double = 4 * (width + length + height) fun save(width: Double, length: Double, height: Double) { this.width = width this.length = length this.height = height } }
fundamental-android-practice/MyUnitTest/app/src/main/java/dev/rushia/myunittest/CuboidModel.kt
1536149473
package dev.rushia.myquote import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.myquote", appContext.packageName) } }
fundamental-android-practice/MyQuote/app/src/androidTest/java/dev/rushia/myquote/ExampleInstrumentedTest.kt
1340338723
package dev.rushia.myquote 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) } }
fundamental-android-practice/MyQuote/app/src/test/java/dev/rushia/myquote/ExampleUnitTest.kt
3282173975
package dev.rushia.myquote import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import com.loopj.android.http.AsyncHttpClient import com.loopj.android.http.AsyncHttpResponseHandler import cz.msebera.android.httpclient.Header import dev.rushia.myquote.databinding.ActivityMainBinding import org.json.JSONObject class MainActivity : AppCompatActivity() { companion object { private val TAG = MainActivity::class.java.simpleName } private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) getRandomObject() binding.btnAllQuotes.setOnClickListener { startActivity(Intent(this@MainActivity, ListQuotesActivity::class.java)) } } private fun getRandomObject() { binding.progressBar.visibility = View.VISIBLE val client = AsyncHttpClient() val url = "https://quote-api.dicoding.dev/random" client.get(url, object : AsyncHttpResponseHandler() { override fun onSuccess( statusCode: Int, headers: Array<out Header>, responseBody: ByteArray ) { // IF SUCCESS binding.progressBar.visibility = View.INVISIBLE val result = String(responseBody) Log.d(TAG, result) try { val responseObject = JSONObject(result) val quote = responseObject.getString("en") val author = responseObject.getString("author") binding.tvQuote.text = quote binding.tvAuthor.text = author } catch (e: Exception) { Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_SHORT).show() e.printStackTrace() } } override fun onFailure( statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable? ) { // IF ERROR binding.progressBar.visibility = View.INVISIBLE val errorMessage = when (statusCode) { 401 -> "$statusCode : Bad Request" 403 -> "$statusCode : Forbidden" 404 -> "$statusCode : Not Found" else -> "$statusCode : ${error?.message}" } Toast.makeText(this@MainActivity, "Error : $errorMessage", Toast.LENGTH_SHORT) .show() } }) } }
fundamental-android-practice/MyQuote/app/src/main/java/dev/rushia/myquote/MainActivity.kt
1619103329
package dev.rushia.myquote import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.loopj.android.http.AsyncHttpClient import com.loopj.android.http.AsyncHttpResponseHandler import cz.msebera.android.httpclient.Header import dev.rushia.myquote.databinding.ActivityListQuotesBinding import org.json.JSONArray class ListQuotesActivity : AppCompatActivity() { companion object { private val TAG = ListQuotesActivity::class.java.simpleName } private lateinit var binding: ActivityListQuotesBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityListQuotesBinding.inflate(layoutInflater) setContentView(binding.root) val layoutManager = LinearLayoutManager(this) binding.listQuotes.layoutManager = layoutManager val itemDecoration = DividerItemDecoration(this, layoutManager.orientation) binding.listQuotes.addItemDecoration(itemDecoration) getListQuotes() } private fun getListQuotes() { binding.progressBar.visibility = View.VISIBLE val client = AsyncHttpClient() val url = "https://quote-api.dicoding.dev/list" client.get(url, object : AsyncHttpResponseHandler() { override fun onSuccess( statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray ) { binding.progressBar.visibility = View.INVISIBLE val listQuote = ArrayList<String>() val res = String(responseBody) Log.d(TAG, res) try { val jsonArray = JSONArray(res) for (i in 0 until jsonArray.length()) { val jsonObject = jsonArray.getJSONObject(i) val quote = jsonObject.getString("en") val author = jsonObject.getString("author") listQuote.add("\n$quote\n — $author\n") } val adapter = QuoteAdapter(listQuote) binding.listQuotes.adapter = adapter } catch (e: Exception) { Toast.makeText(this@ListQuotesActivity, e.message, Toast.LENGTH_SHORT).show() e.printStackTrace() } } override fun onFailure( statusCode: Int, headers: Array<out Header>?, responseBody: ByteArray?, error: Throwable ) { binding.progressBar.visibility = View.INVISIBLE val errorMessage = when (statusCode) { 401 -> "$statusCode : Bad Request" 403 -> "$statusCode : Forbidden" 404 -> "$statusCode : Not Found" else -> "$statusCode : ${error.message}" } Toast.makeText(this@ListQuotesActivity, errorMessage, Toast.LENGTH_SHORT).show() } }) } }
fundamental-android-practice/MyQuote/app/src/main/java/dev/rushia/myquote/ListQuotesActivity.kt
1924111885
package dev.rushia.myquote import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class QuoteAdapter(private val listReview: ArrayList<String>) : RecyclerView.Adapter<QuoteAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuoteAdapter.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_quote, parent, false) return ViewHolder(view) } override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { viewHolder.tvItem.text = listReview[position] } override fun getItemCount(): Int { return listReview.size } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val tvItem: TextView = view.findViewById(R.id.tvItem) } }
fundamental-android-practice/MyQuote/app/src/main/java/dev/rushia/myquote/QuoteAdapter.kt
3342921231
package dev.rushia.mytablayout import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mytablayout", appContext.packageName) } }
fundamental-android-practice/MyTabLayout/app/src/androidTest/java/dev/rushia/mytablayout/ExampleInstrumentedTest.kt
2176256834
package dev.rushia.mytablayout 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) } }
fundamental-android-practice/MyTabLayout/app/src/test/java/dev/rushia/mytablayout/ExampleUnitTest.kt
1850689498
package dev.rushia.mytablayout import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.annotation.StringRes import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator class MainActivity : AppCompatActivity() { companion object{ @StringRes private val TAB_TITLES = intArrayOf( R.string.tab_text_1, R.string.tab_text_2 ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sectionPagerAdapter = SectionsPagerAdapter(this) val viewPager: ViewPager2 = findViewById(R.id.view_pager) viewPager.adapter = sectionPagerAdapter val tabs: TabLayout = findViewById(R.id.tabs) TabLayoutMediator(tabs, viewPager) { tab, position -> tab.text = resources.getString(TAB_TITLES[position]) }.attach() supportActionBar?.elevation = 0f } }
fundamental-android-practice/MyTabLayout/app/src/main/java/dev/rushia/mytablayout/MainActivity.kt
2874316830
package dev.rushia.mytablayout import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter class SectionsPagerAdapter(activity: AppCompatActivity) : FragmentStateAdapter(activity) { override fun getItemCount(): Int { return 2 } override fun createFragment(position: Int): Fragment { var fragment: Fragment? = null when(position){ 0 -> fragment = HomeFragment() 1 -> fragment = ProfileFragment() } return fragment as Fragment } }
fundamental-android-practice/MyTabLayout/app/src/main/java/dev/rushia/mytablayout/SectionsPagerAdapter.kt
559879340
package dev.rushia.mytablayout import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [HomeFragment.newInstance] factory method to * create an instance of this fragment. */ class HomeFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_home, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment HomeFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = HomeFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
fundamental-android-practice/MyTabLayout/app/src/main/java/dev/rushia/mytablayout/HomeFragment.kt
3191368462
package dev.rushia.mytablayout import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [ProfileFragment.newInstance] factory method to * create an instance of this fragment. */ class ProfileFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_profile, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ProfileFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ProfileFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
fundamental-android-practice/MyTabLayout/app/src/main/java/dev/rushia/mytablayout/ProfileFragment.kt
564703587
package dev.rushia.simplenotif import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.simplenotif", appContext.packageName) } }
fundamental-android-practice/SimpleNotif/app/src/androidTest/java/dev/rushia/simplenotif/ExampleInstrumentedTest.kt
728447167
package dev.rushia.simplenotif 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) } }
fundamental-android-practice/SimpleNotif/app/src/test/java/dev/rushia/simplenotif/ExampleUnitTest.kt
3224230147
package dev.rushia.simplenotif import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import dev.rushia.simplenotif.databinding.ActivityDetailBinding class DetailActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) val title = intent.getStringExtra(EXTRA_TITLE) val message = intent.getStringExtra(EXTRA_MESSAGE) binding.tvTitle.text = title binding.tvMessage.text = message } companion object { const val EXTRA_TITLE = "extra_title" const val EXTRA_MESSAGE = "extra_message" } }
fundamental-android-practice/SimpleNotif/app/src/main/java/dev/rushia/simplenotif/DetailActivity.kt
108760159
package dev.rushia.simplenotif import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.TaskStackBuilder import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.NotificationCompat import dev.rushia.simplenotif.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { Toast.makeText(this, "Notifications permission granted", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Notifications permission rejected", Toast.LENGTH_SHORT).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) if (Build.VERSION.SDK_INT >= 33) { requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) } val title = getString(R.string.notification_title) val message = getString(R.string.notification_message) binding.btnSendNotification.setOnClickListener { sendNotification(title, message) } binding.btnOpenDetail.setOnClickListener { val detailIntent = Intent(this@MainActivity, DetailActivity::class.java) detailIntent.putExtra(DetailActivity.EXTRA_TITLE, title) detailIntent.putExtra(DetailActivity.EXTRA_MESSAGE, message) startActivity(detailIntent) } } private fun sendNotification(title: String, message: String) { val notifDetailIntent = Intent(this, DetailActivity::class.java) notifDetailIntent.putExtra(DetailActivity.EXTRA_TITLE, title) notifDetailIntent.putExtra(DetailActivity.EXTRA_MESSAGE, message) val pendingIntent = TaskStackBuilder.create(this).run { addNextIntentWithParentStack(notifDetailIntent) getPendingIntent( NOTIFICATION_ID, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle(title) .setSmallIcon(R.drawable.baseline_notifications_active_24) .setContentText(message) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setSubText(getString(R.string.notification_subtext)) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT ) builder.setChannelId(CHANNEL_ID) notificationManager.createNotificationChannel(channel) } val notification = builder.build() notificationManager.notify(NOTIFICATION_ID, notification) } companion object { private const val NOTIFICATION_ID = 1 private const val CHANNEL_ID = "channel_01" private const val CHANNEL_NAME = "dicoding channel" } }
fundamental-android-practice/SimpleNotif/app/src/main/java/dev/rushia/simplenotif/MainActivity.kt
386980549
package dev.rushia.mydatastore import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mydatastore", appContext.packageName) } }
fundamental-android-practice/MyDataStore/app/src/androidTest/java/dev/rushia/mydatastore/ExampleInstrumentedTest.kt
66674586
package dev.rushia.mydatastore 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) } }
fundamental-android-practice/MyDataStore/app/src/test/java/dev/rushia/mydatastore/ExampleUnitTest.kt
2830316204
package dev.rushia.mydatastore import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch class MainViewModel(private val pref: SettingPreferences) : ViewModel() { fun getThemeSettings(): LiveData<Boolean> { return pref.getThemeSetting().asLiveData() } fun saveThemeSetting(isDarkModeActive: Boolean) { viewModelScope.launch { pref.saveThemeSetting(isDarkModeActive) } } }
fundamental-android-practice/MyDataStore/app/src/main/java/dev/rushia/mydatastore/MainViewModel.kt
525669154
package dev.rushia.mydatastore import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.CompoundButton import androidx.appcompat.app.AppCompatDelegate import androidx.lifecycle.ViewModelProvider import dev.rushia.mydatastore.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val pref = SettingPreferences.getInstance(application.dataStore) val mainViewModel = ViewModelProvider(this, ViewModelFactory(pref)).get( MainViewModel::class.java ) mainViewModel.getThemeSettings().observe(this) { isDarkModeActive: Boolean -> if (isDarkModeActive) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) binding.switchTheme.isChecked = true } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) binding.switchTheme.isChecked = false } } binding.switchTheme.setOnCheckedChangeListener() { _: CompoundButton?, isChecked: Boolean -> mainViewModel.saveThemeSetting(isChecked) } } }
fundamental-android-practice/MyDataStore/app/src/main/java/dev/rushia/mydatastore/MainActivity.kt
2632815900
package dev.rushia.mydatastore import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class ViewModelFactory(private val pref: SettingPreferences) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) { return MainViewModel(pref) as T } throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.name) } }
fundamental-android-practice/MyDataStore/app/src/main/java/dev/rushia/mydatastore/ViewModelFactory.kt
2704292774
package dev.rushia.mydatastore import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.preferencesDataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") class SettingPreferences private constructor(private val dataStore: DataStore<Preferences>) { companion object { @Volatile private var INSTANCE: SettingPreferences? = null fun getInstance(dataStore: DataStore<Preferences>): SettingPreferences { return INSTANCE ?: synchronized(this) { val instance = SettingPreferences(dataStore) INSTANCE = instance instance } } } private val THEME_KEY = booleanPreferencesKey("theme_setting") fun getThemeSetting(): Flow<Boolean> { return dataStore.data.map { preferences -> preferences[THEME_KEY] ?: false } } suspend fun saveThemeSetting(isDarkModeActive: Boolean) { dataStore.edit { preferences -> preferences[THEME_KEY] = isDarkModeActive } } }
fundamental-android-practice/MyDataStore/app/src/main/java/dev/rushia/mydatastore/SettingPreferences.kt
3747764186
package dev.rushia.mynotesapp import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.rushia.mynotesapp", appContext.packageName) } }
fundamental-android-practice/MyNotesApp/app/src/androidTest/java/dev/rushia/mynotesapp/ExampleInstrumentedTest.kt
727763463
package dev.rushia.mynotesapp 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) } }
fundamental-android-practice/MyNotesApp/app/src/test/java/dev/rushia/mynotesapp/ExampleUnitTest.kt
1485317656
package dev.rushia.mynotesapp import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.PersistableBundle import android.view.View import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.snackbar.Snackbar import dev.rushia.mynotesapp.databinding.ActivityMainBinding import dev.rushia.mynotesapp.db.NoteHelper import dev.rushia.mynotesapp.entity.Note import dev.rushia.mynotesapp.helper.MappingHelper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var adapter: NoteAdapter val resultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> if (result.data != null) { // Akan dipanggil jika request codenya ADD when (result.resultCode) { NoteAddUpdateActivity.RESULT_ADD -> { val note = result.data?.getParcelableExtra<Note>(NoteAddUpdateActivity.EXTRA_NOTE) as Note adapter.addItem(note) binding.rvNotes.smoothScrollToPosition(adapter.itemCount - 1) showSnackbarMessage("Satu item berhasil ditambahkan") } NoteAddUpdateActivity.RESULT_UPDATE -> { val note = result.data?.getParcelableExtra<Note>(NoteAddUpdateActivity.EXTRA_NOTE) as Note val position = result?.data?.getIntExtra(NoteAddUpdateActivity.EXTRA_POSITION, 0) as Int adapter.updateItem(position, note) binding.rvNotes.smoothScrollToPosition(position) showSnackbarMessage("Satu item berhasil diubah") } NoteAddUpdateActivity.RESULT_DELETE -> { val position = result?.data?.getIntExtra(NoteAddUpdateActivity.EXTRA_POSITION, 0) as Int adapter.removeItem(position) showSnackbarMessage("Satu item berhasil dihapus") } } } } companion object { private const val EXTRA_STATE = "EXTRA_STATE" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) supportActionBar?.title = "Notes" binding.rvNotes.layoutManager = LinearLayoutManager(this) binding.rvNotes.setHasFixedSize(true) adapter = NoteAdapter(object : NoteAdapter.OnItemClickCallback { override fun onItemClicked(selectionNote: Note?, position: Int) { val intent = Intent(this@MainActivity, NoteAddUpdateActivity::class.java) intent.putExtra(NoteAddUpdateActivity.EXTRA_NOTE, selectionNote) intent.putExtra(NoteAddUpdateActivity.EXTRA_POSITION, position) resultLauncher.launch(intent) } }) binding.rvNotes.adapter = adapter binding.fabAdd.setOnClickListener { val intent = Intent(this@MainActivity, NoteAddUpdateActivity::class.java) resultLauncher.launch(intent) } loadNotesAsync() if (savedInstanceState == null) { // proses ambil data loadNotesAsync() } else { val list = savedInstanceState.getParcelableArrayList<Note>(EXTRA_STATE) if (list != null) { adapter.listNotes = list } } } override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) { super.onSaveInstanceState(outState, outPersistentState) outState.putParcelableArrayList(EXTRA_STATE, adapter.listNotes) } private fun loadNotesAsync() { lifecycleScope.launch { binding.progressbar.visibility = View.VISIBLE val noteHelper = NoteHelper.getInstance(applicationContext) noteHelper.open() val deferredNotes = async(Dispatchers.IO) { val cursor = noteHelper.queryAll() MappingHelper.mapCursorToArrayList(cursor) } binding.progressbar.visibility = View.INVISIBLE val notes = deferredNotes.await() if (notes.size > 0) { adapter.listNotes = notes } else { adapter.listNotes = ArrayList() showSnackbarMessage("Tidak ada data saat ini") } noteHelper.close() } } private fun showSnackbarMessage(message: String) { Snackbar.make(binding.rvNotes, message, Snackbar.LENGTH_SHORT).show() } }
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/MainActivity.kt
2498163447
package dev.rushia.mynotesapp import android.content.ContentValues import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog import dev.rushia.mynotesapp.databinding.ActivityNoteAddUpdateBinding import dev.rushia.mynotesapp.db.DatabaseContract import dev.rushia.mynotesapp.db.DatabaseContract.NoteColumns.Companion.DATE import dev.rushia.mynotesapp.db.NoteHelper import dev.rushia.mynotesapp.entity.Note import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class NoteAddUpdateActivity : AppCompatActivity(), View.OnClickListener { private var isEdit = false private var note: Note? = null private var position: Int = 0 private lateinit var noteHelper: NoteHelper private lateinit var binding: ActivityNoteAddUpdateBinding companion object { const val EXTRA_NOTE = "extra_note" const val EXTRA_POSITION = "extra_position" const val RESULT_ADD = 101 const val RESULT_UPDATE = 201 const val RESULT_DELETE = 301 const val ALERT_DIALOG_CLOSE = 10 const val ALERT_DIALOG_DELETE = 20 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityNoteAddUpdateBinding.inflate(layoutInflater) setContentView(binding.root) noteHelper = NoteHelper.getInstance(applicationContext) noteHelper.open() note = intent.getParcelableExtra(EXTRA_NOTE) if (note != null) { position = intent.getIntExtra(EXTRA_POSITION, 0) isEdit = true } else { note = Note() } val actionBarTitle: String val btnTitle: String if (isEdit) { actionBarTitle = "Ubah" btnTitle = "Update" note?.let { binding.edtTitle.setText(it.title) binding.edtDescription.setText(it.description) } } else { actionBarTitle = "Tambah" btnTitle = "Simpan" } supportActionBar?.title = actionBarTitle supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.btnSubmit.text = btnTitle binding.btnSubmit.setOnClickListener(this) } override fun onClick(view: View) { if (view.id == R.id.btn_submit) { val title = binding.edtTitle.text.toString().trim() val description = binding.edtDescription.text.toString().trim() if (title.isEmpty()) { binding.edtTitle.error = "Field can not be blank" return } note?.title = title note?.description = description val intent = Intent() intent.putExtra(EXTRA_NOTE, note) intent.putExtra(EXTRA_POSITION, position) val values = ContentValues() values.put(DatabaseContract.NoteColumns.TITLE, title) values.put(DatabaseContract.NoteColumns.DESCRIPTION, description) if (isEdit) { val result = noteHelper.update(note?.id.toString(), values).toLong() if (result > 0) { setResult(RESULT_UPDATE, intent) finish() } else { Toast.makeText( this@NoteAddUpdateActivity, "Gagal mengupdate data", Toast.LENGTH_SHORT ).show() } } else { note?.date = getCurrentDate() values.put(DATE, getCurrentDate()) val result = noteHelper.insert(values) if (result > 0) { note?.id = result.toInt() setResult(RESULT_ADD, intent) finish() } else { Toast.makeText( this@NoteAddUpdateActivity, "Gagal menambah data", Toast.LENGTH_SHORT ).show() } } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { if (isEdit) { menuInflater.inflate(R.menu.menu_form, menu) } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_delete -> showAlertDialog(ALERT_DIALOG_DELETE) android.R.id.home -> showAlertDialog(ALERT_DIALOG_CLOSE) } return super.onOptionsItemSelected(item) } override fun onBackPressed() { super.onBackPressed() showAlertDialog(ALERT_DIALOG_CLOSE) } private fun showAlertDialog(type: Int) { val isDialogClose = type == ALERT_DIALOG_CLOSE val dialogTitle: String val dialogMessage: String if (isDialogClose) { dialogTitle = "Batal" dialogMessage = "Apakah anda ingin membatalkan perubahan pada form?" } else { dialogMessage = "Apakah anda yakin ingin menghapus item ini?" dialogTitle = "Hapus Note" } val alertDialogBuilder = AlertDialog.Builder(this) alertDialogBuilder.setTitle(dialogTitle) alertDialogBuilder .setMessage(dialogMessage) .setCancelable(false) .setPositiveButton("Ya") { _, _ -> if (isDialogClose) { finish() } else { val result = noteHelper.deleteById(note?.id.toString()).toLong() if (result > 0) { val intent = Intent() intent.putExtra(EXTRA_POSITION, position) setResult(RESULT_DELETE, intent) finish() } else { Toast.makeText( this@NoteAddUpdateActivity, "Gagal menghapus data", Toast.LENGTH_SHORT ).show() } } } .setNegativeButton("Tidak") { dialog, _ -> dialog.cancel() } val alertDialog = alertDialogBuilder.create() alertDialog.show() } private fun getCurrentDate(): String { val dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()) val date = Date() return dateFormat.format(date) } }
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/NoteAddUpdateActivity.kt
3655568762
package dev.rushia.mynotesapp.entity import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Note( var id: Int = 0, var title: String? = null, var description: String? = null, var date: String? = null ) : Parcelable
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/entity/Note.kt
4073980821
package dev.rushia.mynotesapp.db import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import java.sql.SQLException import kotlin.jvm.Throws class NoteHelper(context: Context) { private var databaseHelper: DatabaseHelper = DatabaseHelper(context) private lateinit var database: SQLiteDatabase @Throws(SQLException::class) fun open() { database = databaseHelper.writableDatabase } fun close() { databaseHelper.close() if (database.isOpen) database.close() } fun queryAll(): Cursor { return database.query( DatabaseContract.NoteColumns.TABLE_NAME, null, null, null, null, null, "${DatabaseContract.NoteColumns._ID} ASC" ) } fun queryById(id: String): Cursor { return database.query( DatabaseContract.NoteColumns.TABLE_NAME, null, "${DatabaseContract.NoteColumns._ID} = ?", arrayOf(id), null, null, null, null, ) } fun insert(values: ContentValues): Long { return database.insert(DatabaseContract.NoteColumns.TABLE_NAME, null, values) } fun update(id: String, values: ContentValues?): Int { return database.update( DatabaseContract.NoteColumns.TABLE_NAME, values, "${DatabaseContract.NoteColumns._ID} = ?", arrayOf(id) ) } fun deleteById(id: String): Int { return database.delete( DatabaseContract.NoteColumns.TABLE_NAME, "${DatabaseContract.NoteColumns._ID} = '$id'", null ) } companion object { private const val DATABASE_TITLE = DatabaseContract.NoteColumns.TABLE_NAME private var INSTANCE: NoteHelper? = null fun getInstance(context: Context): NoteHelper = INSTANCE ?: synchronized(this) { INSTANCE ?: NoteHelper(context) } } }
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/db/NoteHelper.kt
2765214701
package dev.rushia.mynotesapp.db import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import dev.rushia.mynotesapp.db.DatabaseContract.NoteColumns internal class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { companion object { private const val DATABASE_NAME = "dbnotesapp" private const val DATABASE_VERSION = 1 private const val SQL_CREATE_TABLE_NOTE = "CREATE TABLE ${NoteColumns.TABLE_NAME}" + " (${NoteColumns._ID} INTEGER PRIMARY KEY AUTOINCREMENT," + " ${NoteColumns.TITLE} TEXT NOT NULL," + " ${NoteColumns.DESCRIPTION} TEXT NOT NULL," + " ${NoteColumns.DATE} TEXT NOT NULL)" } override fun onCreate(db: SQLiteDatabase) { db.execSQL(SQL_CREATE_TABLE_NOTE) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS ${NoteColumns.TABLE_NAME}") onCreate(db) } }
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/db/DatabaseHelper.kt
2113204003
package dev.rushia.mynotesapp.db import android.provider.BaseColumns internal class DatabaseContract { internal class NoteColumns : BaseColumns { companion object { const val TABLE_NAME = "note" const val _ID = "_id" const val TITLE = "title" const val DESCRIPTION = "description" const val DATE = "date" } } }
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/db/DatabaseContract.kt
1433144482
package dev.rushia.mynotesapp import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import dev.rushia.mynotesapp.databinding.ItemNoteBinding import dev.rushia.mynotesapp.entity.Note class NoteAdapter(private val onItemClickCallback: OnItemClickCallback) : RecyclerView.Adapter<NoteAdapter.NoteViewHolder>() { var listNotes = ArrayList<Note>() set(listNotes) { if (listNotes.size > 0) { this.listNotes.clear() } this.listNotes.addAll(listNotes) } interface OnItemClickCallback { fun onItemClicked(selectionNote: Note?, position: Int) } fun addItem(note: Note) { this.listNotes.add(note) notifyItemInserted(this.listNotes.size - 1) } fun updateItem(position: Int, note: Note) { this.listNotes[position] = note notifyItemChanged(position, note) } fun removeItem(position: Int) { this.listNotes.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, this.listNotes.size) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_note, parent, false) return NoteViewHolder(view) } override fun getItemCount(): Int = this.listNotes.size override fun onBindViewHolder(holder: NoteViewHolder, position: Int) { holder.bind(listNotes[position]) } inner class NoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding = ItemNoteBinding.bind(itemView) fun bind(note: Note) { binding.tvItemTitle.text = note.title binding.tvItemDate.text = note.date binding.tvItemDescription.text = note.description binding.cvItemNote.setOnClickListener { onItemClickCallback.onItemClicked(note, adapterPosition) } } } }
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/NoteAdapter.kt
2635970638
package dev.rushia.mynotesapp.helper import android.database.Cursor import dev.rushia.mynotesapp.db.DatabaseContract import dev.rushia.mynotesapp.entity.Note object MappingHelper { fun mapCursorToArrayList(notesCursor: Cursor?): ArrayList<Note> { val notesList = ArrayList<Note>() notesCursor?.apply { while (moveToNext()) { val id = getInt(getColumnIndexOrThrow(DatabaseContract.NoteColumns._ID)) val title = getString(getColumnIndexOrThrow(DatabaseContract.NoteColumns.TITLE)) val description = getString(getColumnIndexOrThrow(DatabaseContract.NoteColumns.DESCRIPTION)) val date = getString(getColumnIndexOrThrow(DatabaseContract.NoteColumns.DATE)) notesList.add(Note(id, title, description, date)) } } return notesList } }
fundamental-android-practice/MyNotesApp/app/src/main/java/dev/rushia/mynotesapp/helper/MappingHelper.kt
4010778693
package com.dalfior.calculadoradeimccompose 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.dalfior.calculadoradeimccompose", appContext.packageName) } }
CalculadoraImcCompose/app/src/androidTest/java/com/dalfior/calculadoradeimccompose/ExampleInstrumentedTest.kt
2687839426
package com.dalfior.calculadoradeimccompose 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) } }
CalculadoraImcCompose/app/src/test/java/com/dalfior/calculadoradeimccompose/ExampleUnitTest.kt
577577828
package com.dalfior.calculadoradeimccompose.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) val LIGHT_BLUE = Color(0xFF2196F3) val DARK_BLUE = Color(0xFF11568D) val WHITE = Color(0xFFFFFFFF)
CalculadoraImcCompose/app/src/main/java/com/dalfior/calculadoradeimccompose/ui/theme/Color.kt
1574336540
package com.dalfior.calculadoradeimccompose.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 CalculadoraDeImcComposeTheme( 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 ) }
CalculadoraImcCompose/app/src/main/java/com/dalfior/calculadoradeimccompose/ui/theme/Theme.kt
2372307745
package com.dalfior.calculadoradeimccompose.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 ) */ )
CalculadoraImcCompose/app/src/main/java/com/dalfior/calculadoradeimccompose/ui/theme/Type.kt
1064411855
package com.dalfior.calculadoradeimccompose import android.annotation.SuppressLint import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults //import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField //import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold //import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType //import androidx.compose.ui.Modifier //import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.dalfior.calculadoradeimccompose.calculo.CalcularImc import com.dalfior.calculadoradeimccompose.ui.theme.CalculadoraDeImcComposeTheme import com.dalfior.calculadoradeimccompose.ui.theme.DARK_BLUE import com.dalfior.calculadoradeimccompose.ui.theme.LIGHT_BLUE import com.dalfior.calculadoradeimccompose.ui.theme.WHITE //import kotlin.random.Random class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CalculadoraDeImcComposeTheme { DefaultPreview() } } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Stable @Composable fun CalculadoraImc() { val context = LocalContext.current val calcularImc = CalcularImc() var peso by remember { mutableStateOf("") } var altura by remember { mutableStateOf("") } var textoResultado by remember { mutableStateOf("") } Scaffold( topBar = { TopAppBar( title = { Text(text = "Calculadora de IMC", color = WHITE)}, colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = LIGHT_BLUE), actions = { IconButton( onClick = { peso = "" altura = "" textoResultado = "" }, ) { Image(imageVector = ImageVector.vectorResource(id = R.drawable.ic_refresh), contentDescription = "Ícone para resetar todos os campos" ) } } ) } ) {innerPadding -> Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(innerPadding) .fillMaxWidth() .fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Calculadora de IMC", fontSize = 25.sp, fontWeight = FontWeight.Bold, color = LIGHT_BLUE, modifier = Modifier.padding(50.dp) ) OutlinedTextField( value = peso, onValueChange = { peso = it }, label = { Text(text = "Peso (Kg)") }, colors = TextFieldDefaults.outlinedTextFieldColors( cursorColor = LIGHT_BLUE, focusedBorderColor = LIGHT_BLUE, textColor = DARK_BLUE, focusedLabelColor = DARK_BLUE ), textStyle = TextStyle(DARK_BLUE, 18.sp), maxLines = 1, singleLine = true, modifier = Modifier .fillMaxWidth() .padding(20.dp, 0.dp, 20.dp, 0.dp), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number ) ) OutlinedTextField( value = altura, onValueChange = { altura = it }, label = { Text(text = "Altura") }, colors = TextFieldDefaults.outlinedTextFieldColors( cursorColor = LIGHT_BLUE, focusedBorderColor = LIGHT_BLUE, textColor = DARK_BLUE, focusedLabelColor = DARK_BLUE ), textStyle = TextStyle(DARK_BLUE, 18.sp), maxLines = 1, singleLine = true, modifier = Modifier .fillMaxWidth() .padding(20.dp, 10.dp, 20.dp, 0.dp), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number ) ) Button( onClick = { if (peso.isEmpty() || altura.isEmpty()){ Toast.makeText(context, "Preencha todos os campos!", Toast.LENGTH_SHORT).show() }else{ calcularImc.calcularImc(peso, altura) textoResultado = calcularImc.resultadoImc() } }, modifier = Modifier .fillMaxWidth() .padding(20.dp) .height(50.dp), colors = ButtonDefaults.buttonColors( containerColor = LIGHT_BLUE, contentColor = WHITE ) ) { Text(text = "Calcular IMC", fontSize = 18.sp, fontWeight = FontWeight.Bold ) } Text( text = textoResultado, fontSize = 18.sp, color = DARK_BLUE, fontWeight = FontWeight.Bold ) } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { CalculadoraDeImcComposeTheme { CalculadoraImc() } }
CalculadoraImcCompose/app/src/main/java/com/dalfior/calculadoradeimccompose/MainActivity.kt
4238807439
package com.dalfior.calculadoradeimccompose.calculo import java.text.DecimalFormat class CalcularImc { private var resultadoImc = "" fun calcularImc(peso: String, altura: String) { val pesoConvertido = peso.toDouble() val alturaConvertido = altura.toDouble() val resultado: String val imc = pesoConvertido / (alturaConvertido * alturaConvertido) val decimalFormat = DecimalFormat("0.00") if (imc <= 18.5){ resultado = "Peso baixo \n IMC: ${decimalFormat.format(imc)}" }else if (imc <= 24.9){ resultado = "Peso normal \n IMC: ${decimalFormat.format(imc)}" }else if (imc <= 29.9){ resultado = "Sobrepeso \n IMC: ${decimalFormat.format(imc)}" }else if (imc <= 34.9){ resultado = "Obedidade (Grau 1) \n IMC: ${decimalFormat.format(imc)}" }else if (imc <= 39.9){ resultado = "Obesidade severa (Grau 2) \n IMC: ${decimalFormat.format(imc)}" }else{ resultado = "Obesidade mórbida (Grau 3) \n IMC: ${decimalFormat.format(imc)}" } resultadoImc = resultado } fun resultadoImc(): String{ return resultadoImc } }
CalculadoraImcCompose/app/src/main/java/com/dalfior/calculadoradeimccompose/calculo/CalcularImc.kt
1887904114
package com.asgar72.kidsdrawing 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.asgar72.kidsdrawing", appContext.packageName) } }
Kids-Drawing-App/app/src/androidTest/java/com/asgar72/kidsdrawing/ExampleInstrumentedTest.kt
2327467742
package com.asgar72.kidsdrawing 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) } }
Kids-Drawing-App/app/src/test/java/com/asgar72/kidsdrawing/ExampleUnitTest.kt
2524386475
package com.asgar72.kidsdrawing import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.appcompat.app.ActionBar class MainActivity : AppCompatActivity() { private var drawingView: DrawingView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportActionBar?.hide() drawingView = findViewById(R.id.drawing_view) drawingView?.setSizeForBrush(20.toFloat()) } }
Kids-Drawing-App/app/src/main/java/com/asgar72/kidsdrawing/MainActivity.kt
210648414
package com.asgar72.kidsdrawing import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.util.TypedValue import android.view.MotionEvent import android.view.View import java.lang.reflect.TypeVariable import kotlin.io.path.Path class DrawingView(context: Context, attrs: AttributeSet) : View(context, attrs) { private var mDrawPath: CustomPath? = null // An variable of CustomPath inner class to use it further. private var mCanvasBitmap: Bitmap? = null // An instance of the Bitmap. private var mDrawPaint: Paint? = null // The Paint class holds the style and color information about how to draw geometries, text and bitmaps. private var mCanvasPaint: Paint? = null // Instance of canvas paint view. private var mBrushSize: Float = 0.toFloat() // A variable for stroke/brush size to draw on the canvas. // A variable to hold a color of the stroke. private var color = Color.BLACK /** * A variable for canvas which will be initialized later and used. * *The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host * the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, * Path, text, Bitmap), and a paint (to describe the colors and styles for the * drawing) */ private var canvas: Canvas? = null private var mPaths = ArrayList<CustomPath>() init { setUpDrawing() } /** * This method initializes the attributes of the * ViewForDrawing class. */ private fun setUpDrawing() { mDrawPaint = Paint() mDrawPath = CustomPath(color, mBrushSize) mDrawPaint!!.color = color mDrawPaint!!.style = Paint.Style.STROKE // This is to draw a STROKE style mDrawPaint!!.strokeJoin = Paint.Join.ROUND // This is for store join mDrawPaint!!.strokeCap = Paint.Cap.ROUND // This is for stroke Cap mCanvasPaint = Paint(Paint.DITHER_FLAG) // Paint flag that enables dithering when blitting. //mBrushSize = 20.toFloat() //Here the default or we can initial brush size } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) mCanvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) canvas = Canvas(mCanvasBitmap!!) } /** * This method is called when a stroke is drawn on the canvas * as a part of the painting. */ override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawBitmap(mCanvasBitmap!!, 0f, 0f, mCanvasPaint) /** * Draw the specified bitmap, with its top/left corner at (x,y), using the specified paint, * transformed by the current matrix. * *If the bitmap and canvas have different densities, this function will take care of * automatically scaling the bitmap to draw at the same density as the canvas. * * @param bitmap The bitmap to be drawn * @param left The position of the left side of the bitmap being drawn * @param top The position of the top side of the bitmap being drawn * @param paint The paint used to draw the bitmap (may be null) */ for (path in mPaths) { mDrawPaint!!.strokeWidth = path.brushThickness mDrawPaint!!.color = path.color canvas.drawPath(path, mDrawPaint!!) } if (!mDrawPath!!.isEmpty) { mDrawPaint!!.strokeWidth = mDrawPath!!.brushThickness mDrawPaint!!.color = mDrawPath!!.color canvas.drawPath(mDrawPath!!, mDrawPaint!!) } } /** * This method acts as an event listener when a touch * event is detected on the device. */ override fun onTouchEvent(event: MotionEvent?): Boolean { val touchX = event?.x val touchY = event?.y when (event?.action) { MotionEvent.ACTION_DOWN -> { mDrawPath!!.color = color mDrawPath!!.brushThickness = mBrushSize mDrawPath!!.reset() if (touchX != null) { if (touchY != null) { mDrawPath!!.moveTo(touchX, touchY) } } } MotionEvent.ACTION_MOVE -> { if (touchX != null) { if (touchY != null) { mDrawPath!!.lineTo(touchX, touchY) } } } MotionEvent.ACTION_UP -> { mPaths.add(mDrawPath!!) mDrawPath = CustomPath(color, mBrushSize) } else -> return false } invalidate() return true } fun setSizeForBrush(newSize: Float) { mBrushSize = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, newSize, resources.displayMetrics ) mDrawPaint!!.strokeWidth = mBrushSize } //An inner class for custom path with two params as color and stroke size. internal inner class CustomPath(var color: Int, var brushThickness: Float) : Path() { } }
Kids-Drawing-App/app/src/main/java/com/asgar72/kidsdrawing/DrawingView.kt
1777837241
package com.example.topquizcmr 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.topquizcmr", appContext.packageName) } }
Mobile_Projet/TopQuizCmr/TopQuizCmr/app/src/androidTest/java/com/example/topquizcmr/ExampleInstrumentedTest.kt
1592833227
package com.example.topquizcmr 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) } }
Mobile_Projet/TopQuizCmr/TopQuizCmr/app/src/test/java/com/example/topquizcmr/ExampleUnitTest.kt
282208279
package com.example.loginuione 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.loginuione", appContext.packageName) } }
Mobile_Projet/Login_Register/LoginUiOne/app/src/androidTest/java/com/example/loginuione/ExampleInstrumentedTest.kt
3177557000
package com.example.loginuione 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) } }
Mobile_Projet/Login_Register/LoginUiOne/app/src/test/java/com/example/loginuione/ExampleUnitTest.kt
1170024278
package com.example.loginuione.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Mobile_Projet/Login_Register/LoginUiOne/app/src/main/java/com/example/loginuione/ui/theme/Shape.kt
2893713088
package com.example.loginuione.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
Mobile_Projet/Login_Register/LoginUiOne/app/src/main/java/com/example/loginuione/ui/theme/Color.kt
2065478410