diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3df81a6..d624e57 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -4,6 +4,14 @@ + + + + + + + + + if (result.resultCode == Activity.RESULT_OK) { + handleCameraImage(result.data) + val uribitmap = result.data?.data + val FILENAME = "image.png" + val PATH = "/mnt/sdcard/$FILENAME" + val f = File(PATH) + val yourUri = Uri.fromFile(f) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + try { + grantUriPermission( + packageName, + uribitmap, + FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_PERSISTABLE_URI_PERMISSION + ) + } catch (e: IllegalArgumentException) { + // on Kitkat api only 0x3 is allowed (FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION) + grantUriPermission( + packageName, + uribitmap, + FLAG_GRANT_READ_URI_PERMISSION + ) + } catch (e: SecurityException) { + Log.e("", e.toString()) + } + try { + var takeFlags = intent.flags + takeFlags = + takeFlags and (FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + uribitmap?.let { contentResolver.takePersistableUriPermission(it, takeFlags) } + } catch (e: SecurityException) { + Log.e("", e.toString()) + } + } + imageUri = uribitmap + if (Build.VERSION.SDK_INT < 11) + realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, uribitmap).toString(); + + // SDK >= 11 && SDK < 19 + else if (Build.VERSION.SDK_INT < 19) + realPath = RealPathUtil.getRealPathFromURI_API11to18(this, uribitmap).toString(); + + // SDK > 19 (Android 4.4) + else + realPath = RealPathUtil.getRealPathFromURI_API19(this, uribitmap).toString(); + } + } + + @SuppressLint("WrongConstant") + private val galleryResult = + registerForActivityResult(ActivityResultContracts.GetContent()) { result -> + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + try { + grantUriPermission( + packageName, + result, + FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_PERSISTABLE_URI_PERMISSION + ) + } catch (e: IllegalArgumentException) { + // on Kitkat api only 0x3 is allowed (FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION) + grantUriPermission( + packageName, + result, + FLAG_GRANT_READ_URI_PERMISSION + ) + } catch (e: SecurityException) { + Log.e("", e.toString()) + } + try { + var takeFlags = intent.flags + takeFlags = + takeFlags and (FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + contentResolver.takePersistableUriPermission(result, takeFlags) + } catch (e: SecurityException) { + Log.e("", e.toString()) + } + } + imageUri = result + if (Build.VERSION.SDK_INT < 11) + realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, result).toString(); + + // SDK >= 11 && SDK < 19 + else if (Build.VERSION.SDK_INT < 19) + realPath = RealPathUtil.getRealPathFromURI_API11to18(this, result).toString(); + + // SDK > 19 (Android 4.4) + else + realPath = RealPathUtil.getRealPathFromURI_API19(this, result).toString(); + binding.ivImage.setImageURI(result) + } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) + + binding.apply { btnLogout.setOnClickListener { //create alerrt dialog - val builder = androidx.appcompat.app.AlertDialog.Builder(this@ProfileActivity) + val builder = AlertDialog.Builder(this@ProfileActivity) builder.setTitle("Logout") builder.setMessage("Are you sure you want to logout?") - builder.setPositiveButton("Yes") { dialog, which -> + builder.setPositiveButton("Yes") { _, _ -> viewModel.clearData() startActivity(Intent(this@ProfileActivity, LoginActivity::class.java)) finish() } - builder.setNegativeButton("No") { dialog, which -> + builder.setNegativeButton("No") { dialog, _ -> dialog.dismiss() } - val dialog: androidx.appcompat.app.AlertDialog = builder.create() + val dialog: AlertDialog = builder.create() dialog.show() } + ivImage.setOnClickListener { + checkingPermissions() + } + btnUpdate.setOnClickListener { val email = edtEmail.text.toString() val username = edtUsername.text.toString() val birthday = edtBirthDate.text.toString() val address = edtAddress.text.toString() - val user = User( email = email, username = username, birthDate = birthday, - address = address, id = userId, password = password) + val user = User( + email = email, username = username, birthDate = birthday, + address = address, id = userId, password = password, profilePicture = realPath + ) user.let { it1 -> viewModel.updateUser(it1) } user.let { it1 -> viewModel.saveUser(it1, true) } @@ -100,6 +229,21 @@ class ProfileActivity : AppCompatActivity() { edtEmail.setText(email) edtBirthDate.setText(birthDate) edtAddress.setText(address) +// Glide.with(this@ProfileActivity) +// .load(File(Uri.parse(profilePicture).path)) +// .into(ivImage); + if (profilePicture != "") { + val imgFile = File(profilePicture) + if (imgFile.exists()) { + realPath = profilePicture.toString() + Glide.with(this@ProfileActivity) + .load(File(Uri.parse(profilePicture).path)) + .into(ivImage); +// ivImage.setImageURI(Uri.parse(profilePicture)) + } + + } +// ivImage.setImageURI(Uri.parse(profilePicture)) } } } @@ -110,4 +254,90 @@ class ProfileActivity : AppCompatActivity() { } } } + + private fun checkingPermissions() { + if (isGranted( + this, + Manifest.permission.CAMERA, + arrayOf( + Manifest.permission.CAMERA, + Manifest.permission.READ_EXTERNAL_STORAGE, + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.MANAGE_DOCUMENTS + ), + REQUEST_CODE_PERMISSION, + ) + ) { + openGallery() + } + } + + private fun isGranted( + activity: Activity, + permission: String, + permissions: Array, + request: Int, + ): Boolean { + val permissionCheck = ActivityCompat.checkSelfPermission(activity, permission) + return if (permissionCheck != PackageManager.PERMISSION_GRANTED) { + if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { + showPermissionDeniedDialog() + } else { + ActivityCompat.requestPermissions(activity, permissions, request) + } + false + } else { + true + } + } + + private fun showPermissionDeniedDialog() { + AlertDialog.Builder(this) + .setTitle("Permission Denied") + .setMessage("Permission is denied, Please allow permissions from App Settings.") + .setPositiveButton( + "App Settings" + ) { _, _ -> + val intent = Intent() + intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS + val uri = Uri.fromParts("package", packageName, null) + intent.data = uri + startActivity(intent) + } + .setNegativeButton("Cancel") { dialog, _ -> dialog.cancel() } + .show() + } + + private fun chooseImageDialog() { + AlertDialog.Builder(this) + .setMessage("Pilih Gambar") + .setPositiveButton("Gallery") { _, _ -> openGallery() } + .setNegativeButton("Camera") { _, _ -> openCamera() } + .show() + } + + private fun openGallery() { + intent.addFlags(FLAG_GRANT_READ_URI_PERMISSION); + intent.addFlags(FLAG_GRANT_PERSISTABLE_URI_PERMISSION); + intent.type = "image/*" + intent.action = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + Intent.ACTION_OPEN_DOCUMENT + } else { + Intent.ACTION_PICK + } + intent.action = Intent.ACTION_OPEN_DOCUMENT + galleryResult.launch("image/*") + } + + private fun openCamera() { + val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) + cameraResult.launch(cameraIntent) + } + + private fun handleCameraImage(intent: Intent?) { + val bitmap = intent?.extras?.get("data") as Bitmap + binding.ivImage.setImageBitmap(bitmap) + } + + } \ No newline at end of file diff --git a/app/src/main/java/com/android/movku/utils/RealPathUtil.kt b/app/src/main/java/com/android/movku/utils/RealPathUtil.kt new file mode 100644 index 0000000..94fcc1e --- /dev/null +++ b/app/src/main/java/com/android/movku/utils/RealPathUtil.kt @@ -0,0 +1,61 @@ +package com.android.movku.utils + +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.MediaStore +import androidx.loader.content.CursorLoader + + +object RealPathUtil { + fun getRealPathFromURI_API19(context: Context, uri: Uri?): String? { + var filePath = "" + val wholeID = DocumentsContract.getDocumentId(uri) + + // Split at colon, use second item in the array + val id = wholeID.split(":").toTypedArray()[1] + val column = arrayOf(MediaStore.Images.Media.DATA) + + // where id is equal to + val sel = MediaStore.Images.Media._ID + "=?" + val cursor: Cursor? = context.getContentResolver().query( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + column, sel, arrayOf(id), null + ) + val columnIndex: Int = cursor?.getColumnIndex(column[0]) ?: 0 + if (cursor?.moveToFirst() == true) { + filePath = cursor.getString(columnIndex) + } + cursor?.close() + return filePath + } + + fun getRealPathFromURI_API11to18(context: Context?, contentUri: Uri?): String? { + val proj = arrayOf(MediaStore.Images.Media.DATA) + var result: String? = null + val cursorLoader = context?.let { + contentUri?.let { it1 -> + CursorLoader( + it, + it1, proj, null, null, null + ) + } + } + val cursor: Cursor? = cursorLoader?.loadInBackground() + if (cursor != null) { + val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) + cursor.moveToFirst() + result = cursor.getString(column_index) + } + return result + } + + fun getRealPathFromURI_BelowAPI11(context: Context, contentUri: Uri?): String? { + val proj = arrayOf(MediaStore.Images.Media.DATA) + val cursor = context.contentResolver.query(contentUri!!, proj, null, null, null) + val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) + cursor.moveToFirst() + return cursor.getString(column_index) + } +} \ No newline at end of file diff --git a/app/src/main/res/layout/activity_profile.xml b/app/src/main/res/layout/activity_profile.xml index 38bfd52..7f1e694 100644 --- a/app/src/main/res/layout/activity_profile.xml +++ b/app/src/main/res/layout/activity_profile.xml @@ -21,9 +21,11 @@ android:textSize="24sp" />