Skip to content
Snippets Groups Projects
Commit 8d9b9f18 authored by Farhan Nabil Suryono's avatar Farhan Nabil Suryono
Browse files

Merge branch 'dev' into 'main'

Merge to main sprint 1

See merge request !17
parents e5adc67e aa54a667
Branches
Tags 1.0 2.0
1 merge request!17Merge to main sprint 1
Showing
with 1941 additions and 87 deletions
root = true
[*]
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
[*.{kt,kts}]
indent_style = tab
indent_size = 4
ktlint_code_style=ktlint_official
ktlint_standard_package-name = disabled
ktlint_standard_no-wildcard-imports = disabled
ktlint_standard_no-consecutive-comments = disabled
\ No newline at end of file
name: Android CI/CD
on:
push:
branches:
- main
- dev
- result-page
- home-page
jobs:
build-and-test:
runs-on: ubuntu-latest
env:
ANDROID_COMPILE_SDK: "34"
SDK_TOOLS: "9477386"
EMULATOR_VERSION: "33"
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up JDK
uses: actions/setup-java@v2
with:
distribution: 'adopt'
java-version: '17'
- name: Install dependencies
run: |
sudo apt-get update -qy
sudo apt-get install -y openjdk-17-jdk unzip
wget --quiet --output-document=android-sdk.zip https://dl.google.com/android/repository/commandlinetools-linux-${{ env.SDK_TOOLS }}_latest.zip
unzip -q android-sdk.zip -d android-sdk-linux
rm android-sdk.zip
export ANDROID_SDK_ROOT=$PWD/android-sdk-linux
mkdir $ANDROID_SDK_ROOT/cmdline-tools/tools
mv $ANDROID_SDK_ROOT/cmdline-tools/{lib,bin,source.properties,NOTICE.txt} $ANDROID_SDK_ROOT/cmdline-tools/tools
mkdir $ANDROID_SDK_ROOT/cmdline-tools/latest
export PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin:$ANDROID_SDK_ROOT/platform-tools
sdkmanager --sdk_root=${ANDROID_SDK_ROOT} --update > update.log
echo y | sdkmanager --sdk_root=${ANDROID_SDK_ROOT} "platforms;android-${ANDROID_COMPILE_SDK}" "extras;google;m2repository" "extras;android;m2repository"
chmod +x ./gradlew
- name: Build project
run: ./gradlew assemble
- name: Run unit tests
run: ./gradlew test
- name: Code formatting
run: ./gradlew spotlessCheck
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
/.idea
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
# OMRekap # OMRekap
## Development
### Clone the repository
## Getting started ```bash
git clone https://gitlab.informatika.org/k-02-09/omrekap
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
``` ```
cd existing_repo
git remote add origin https://gitlab.informatika.org/k-02-09/omrekap.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.informatika.org/k-02-09/omrekap/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. ### Run Unit Test
```bash
## Suggestions for a good README ./gradlew test
```
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License ### Code Formatting
For open source projects, say how it is licensed. ```bash
./gradlew spotlessApply
```
## Project status ### Changing Formatting Configuration
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. * Update spotless.gradle based on Ktlint rules [here](https://pinterest.github.io/ktlint/0.50.0/rules/configuration-ktlint/)
* Clean gradle cache
```bash
./gradlew clean
* ```
/build
\ No newline at end of file
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.k2_9.omrekap"
compileSdk = 34
defaultConfig {
applicationId = "com.k2_9.omrekap"
minSdk = 28
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.11.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
implementation("com.github.chrisbanes:PhotoView:2.3.0")
implementation("androidx.activity:activity-ktx:1.8.2")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0")
// Camera
val cameraxVersion = "1.3.1"
implementation("androidx.camera:camera-core:${cameraxVersion}")
implementation("androidx.camera:camera-camera2:${cameraxVersion}")
implementation("androidx.camera:camera-lifecycle:${cameraxVersion}")
implementation("androidx.camera:camera-view:${cameraxVersion}")
implementation("androidx.camera:camera-extensions:${cameraxVersion}")
// Test
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
\ No newline at end of file
package com.k2_9.omrekap
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* 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.k2_9.omrekap", appContext.packageName)
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Omrekap"
tools:targetApi="31">
<activity
android:name=".activities.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activities.ExpandImageActivity" />
<activity android:name=".activities.CameraActivity" />
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
</application>
</manifest>
app/src/main/ic_launcher-playstore.png

36.5 KiB

package com.k2_9.omrekap.activities
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.AudioManager
import android.media.MediaActionSound
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.view.CameraController
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.k2_9.omrekap.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.concurrent.Executors
class CameraActivity : AppCompatActivity() {
companion object {
const val EXTRA_NAME_IMAGE_URI_STRING = "IMAGE_URI_STRING"
const val EXTRA_NAME_IS_FROM_CAMERA_RESULT = "IS_FROM_CAMERA_RESULT"
}
private var imageUriString: String? = null
private var isFromCameraResult: Boolean = false
private lateinit var previewView: PreviewView
private lateinit var imageView: ImageView
private lateinit var captureButton: ImageButton
private lateinit var imageCapture: ImageCapture
private lateinit var cameraController: CameraController
private fun onBackHome() {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
}
private fun onBackResult() {
val intent = Intent(this, MainActivity::class.java)
intent.putExtra(MainActivity.EXTRA_NAME_IS_RESULT, true)
intent.putExtra(MainActivity.EXTRA_NAME_IMAGE_URI_STRING, imageUriString)
intent.putExtra(MainActivity.EXTRA_NAME_IS_FROM_CAMERA, isFromCameraResult)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
}
private fun handleBackNavigation() {
if (imageUriString == null) {
onBackHome()
} else {
onBackResult()
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null) {
imageUriString = intent.getStringExtra(EXTRA_NAME_IMAGE_URI_STRING)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera)
imageUriString = intent.getStringExtra(EXTRA_NAME_IMAGE_URI_STRING)
isFromCameraResult = intent.getBooleanExtra(EXTRA_NAME_IS_FROM_CAMERA_RESULT, false)
// back navigation
onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
handleBackNavigation()
}
},
)
}
override fun onStart() {
super.onStart()
previewView = findViewById(R.id.preview_view)
imageView = findViewById(R.id.freeze_image_view)
imageView.visibility = View.GONE
previewView.visibility = View.VISIBLE
captureButton = findViewById(R.id.take_photo_button)
captureButton.setOnClickListener {
takePhoto()
}
captureButton.isEnabled = true
requirePermission(Manifest.permission.CAMERA) {
if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.Q) {
requirePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, false) {}
}
imageCapture =
ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.setFlashMode(ImageCapture.FLASH_MODE_ON)
.build()
cameraController = LifecycleCameraController(this)
(cameraController as LifecycleCameraController).bindToLifecycle(this)
cameraController.cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
previewView.controller = cameraController
}
}
private fun requirePermission(
permission: String,
verbose: Boolean = true,
operation: () -> Unit,
) {
if (ContextCompat.checkSelfPermission(
this,
permission,
) == PackageManager.PERMISSION_GRANTED
) {
operation()
} else {
val requestPermissionLauncher =
registerForActivityResult(RequestPermission()) {
isGranted: Boolean ->
if (isGranted) {
operation()
} else {
if (verbose) {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
requestPermissionLauncher.launch(permission)
}
}
suspend fun saveImageOnCache(image: ImageProxy) {
// get current day as sign
val dateString = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
// delete previous file from cache
val outputDir = this@CameraActivity.cacheDir
outputDir.listFiles()?.forEach { file: File? ->
if ((file != null) && file.exists() && file.isFile) {
val sign = file.name.slice(IntRange(0, 9))
if (sign == "temp-image") {
file.delete()
}
}
}
// save temp file on cache
val outputFile = File.createTempFile("temp-image-$dateString", ".png", outputDir)
outputFile.outputStream().use {
image.toBitmap().compress(Bitmap.CompressFormat.PNG, 100, it)
}
// Notify user
val uri = outputFile.toURI()
// send URI to MainActivity
startActivity(
Intent(this, MainActivity::class.java)
.putExtra(MainActivity.EXTRA_NAME_IMAGE_URI_STRING, uri.toString())
.putExtra(MainActivity.EXTRA_NAME_IS_RESULT, true)
.putExtra(MainActivity.EXTRA_NAME_IS_FROM_CAMERA, true)
.putExtra(MainActivity.EXTRA_NAME_IS_RESET, true)
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOP),
)
}
private fun playShutterSound() {
val audio: AudioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
when (audio.ringerMode) {
AudioManager.RINGER_MODE_NORMAL -> {
val sound = MediaActionSound()
sound.play(MediaActionSound.SHUTTER_CLICK)
}
else -> {
// do nothing
}
}
}
private fun freezeImage(image: ImageProxy) {
runOnUiThread {
previewView.visibility = View.GONE
imageView.rotation = 90F
imageView.setImageBitmap(image.toBitmap())
imageView.visibility = View.VISIBLE
captureButton.isEnabled = false
}
}
private fun takePhoto() {
val cameraExecutor = Executors.newSingleThreadExecutor()
cameraController.takePicture(
cameraExecutor,
object :
ImageCapture.OnImageCapturedCallback() {
override fun onError(exception: ImageCaptureException) {
// TODO
}
override fun onCaptureSuccess(image: ImageProxy) {
super.onCaptureSuccess(image)
playShutterSound()
freezeImage(image)
runOnUiThread {
Toast.makeText(this@CameraActivity, "Photo taken", Toast.LENGTH_SHORT).show()
}
lifecycleScope.launch {
withContext(Dispatchers.IO) {
saveImageOnCache(image)
}
}
}
},
)
}
}
package com.k2_9.omrekap.activities
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.github.chrisbanes.photoview.PhotoView
import com.k2_9.omrekap.R
class ExpandImageActivity : AppCompatActivity() {
companion object {
const val EXTRA_NAME_DRAWABLE_RESOURCE = "DRAWABLE_RESOURCE"
const val EXTRA_NAME_IMAGE_RESOURCE = "IMAGE_RESOURCE"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_expand_image)
val photoView: PhotoView = findViewById(R.id.fullscreen_content)
val imageResource = intent.getStringExtra(EXTRA_NAME_IMAGE_RESOURCE)
if (imageResource != null) {
photoView.setImageURI(Uri.parse(imageResource))
} else {
// Retrieve the image resource ID from the intent
val drawableResource = intent.getIntExtra(EXTRA_NAME_DRAWABLE_RESOURCE, 0)
// Set the image resource to PhotoView
if (drawableResource != 0) {
photoView.setImageResource(drawableResource)
} else {
photoView.setImageResource(R.drawable.ic_image)
}
}
}
}
package com.k2_9.omrekap.activities
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import android.widget.ImageButton
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.k2_9.omrekap.R
import com.k2_9.omrekap.fragments.HomePageFragment
import com.k2_9.omrekap.fragments.ResultPageFragment
import com.k2_9.omrekap.models.ImageSaveData
import com.k2_9.omrekap.utils.SaveHelper
import com.k2_9.omrekap.view_models.ImageDataViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivity : AppCompatActivity() {
companion object {
const val EXTRA_NAME_IS_RESULT = "IS_RESULT"
const val EXTRA_NAME_IS_FROM_CAMERA = "IS_FROM_CAMERA"
const val EXTRA_NAME_IMAGE_URI_STRING = "IMAGE_URI_STRING"
const val EXTRA_NAME_IS_RESET = "IS_RESET"
}
private val viewModel: ImageDataViewModel by viewModels()
private var saveFileJob: Job? = null
private var saveFileJobCompleted: Boolean = false
private val omrHelperObserver =
Observer<ImageSaveData> { newValue ->
if (newValue.isProcessed()) {
saveFile()
}
}
private var isResult: Boolean = false
private var isFromCamera: Boolean = false // must be false if isResult is false
private var imageUriString: String? = null // can't be null if isResult is true
private var isReset: Boolean = false // reset ViewModel for new OMR process
private var isCreated = false
private fun onGalleryButtonClick() {
val intent = Intent(this, MainActivity::class.java)
intent.putExtra(EXTRA_NAME_IS_RESULT, true)
intent.putExtra(EXTRA_NAME_IS_RESET, true)
intent.putExtra(EXTRA_NAME_IS_FROM_CAMERA, false)
// TODO: pass image URI from gallery
intent.putExtra(EXTRA_NAME_IMAGE_URI_STRING, imageUriString)
startActivity(intent)
}
private fun onCameraButtonClick() {
val intent = Intent(this, CameraActivity::class.java)
if (isResult) {
intent.putExtra(CameraActivity.EXTRA_NAME_IMAGE_URI_STRING, imageUriString)
intent.putExtra(CameraActivity.EXTRA_NAME_IS_FROM_CAMERA_RESULT, isFromCamera)
}
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
}
private fun saveFile() {
saveFileJob =
lifecycleScope.launch(Dispatchers.IO) {
SaveHelper().save(applicationContext, viewModel.data.value!!)
saveFileJobCompleted = true
withContext(Dispatchers.Main) {
Toast.makeText(
applicationContext,
"File saved in Documents/OMRekap",
Toast.LENGTH_SHORT,
).show()
}
}
}
private fun setFragment() {
// set fragment view
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
var fragment: Fragment? = null
if (isResult) {
// Create an instance of your fragment
fragment = ResultPageFragment()
val arguments =
Bundle().apply {
putBoolean(ResultPageFragment.ARG_NAME_IS_FROM_CAMERA, isFromCamera)
putString(ResultPageFragment.ARG_NAME_IMAGE_URI_STRING, imageUriString)
}
// Set the arguments for the fragment
fragment.arguments = arguments
} else {
fragment = HomePageFragment()
}
fragmentTransaction.replace(R.id.fragment_container_view, fragment)
fragmentTransaction.commit()
}
private fun updateStates(intent: Intent) {
isResult = intent.getBooleanExtra(EXTRA_NAME_IS_RESULT, false)
if (isResult) {
isFromCamera = intent.getBooleanExtra(EXTRA_NAME_IS_FROM_CAMERA, false)
isReset = intent.getBooleanExtra(EXTRA_NAME_IS_RESET, false)
imageUriString = intent.getStringExtra(EXTRA_NAME_IMAGE_URI_STRING)
if (imageUriString == null) {
throw IllegalArgumentException("Image URI string is null")
}
if (isReset) {
// TODO: reset view model
if (isCreated) {
setFragment()
}
}
if (viewModel.data.value == null || !viewModel.data.value!!.isProcessed()) {
viewModel.processImage(Uri.parse(imageUriString))
viewModel.data.observe(this, omrHelperObserver)
}
if (!isFromCamera && !saveFileJobCompleted && viewModel.data.value!!.isProcessed()) {
saveFile()
}
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null) {
if (isCreated && (isResult.xor(intent.getBooleanExtra(EXTRA_NAME_IS_RESULT, false)))) {
// wrong activity reused, restarting the new intent and finishing this activity
val newIntent = Intent(this, MainActivity::class.java)
val extras = Bundle(intent.extras)
newIntent.putExtras(extras)
if (isResult) {
// if want to go to home page but found result page on stack
// remove this activity from stack and continue to find reusable homepage
newIntent.addFlags(intent.flags)
finish()
}
// if want to reuse result page but found home page, leave this home page activity
// just create new result page
startActivity(newIntent)
} else {
updateStates(intent)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
saveFileJobCompleted = savedInstanceState?.getBoolean("saveFileJobCompleted") ?: false
updateStates(intent)
assert(!isFromCamera || isResult)
// fix shadow
val galleryCardView: CardView = findViewById(R.id.gallery_card_view)
val cameraCardView: CardView = findViewById(R.id.camera_card_view)
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
galleryCardView.elevation = 0f
cameraCardView.elevation = 0f
}
setFragment()
// add button listeners
val galleryButton: ImageButton = findViewById(R.id.gallery_button)
val cameraButton: ImageButton = findViewById(R.id.camera_button)
galleryButton.setOnClickListener {
onGalleryButtonClick()
}
cameraButton.setOnClickListener {
onCameraButtonClick()
}
isCreated = true
}
override fun onSaveInstanceState(
outState: Bundle,
outPersistentState: PersistableBundle,
) {
super.onSaveInstanceState(outState, outPersistentState)
outState.putBoolean("saveFileJobCompleted", saveFileJobCompleted)
}
override fun onDestroy() {
super.onDestroy()
saveFileJob?.cancel()
}
}
package com.k2_9.omrekap.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.k2_9.omrekap.R
class ResultAdapter(private val dataList: List<Pair<String, String>>) :
RecyclerView.Adapter<ResultAdapter.ResultViewHolder>() {
inner class ResultViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val keyTextView: TextView = itemView.findViewById(R.id.result_candidate_text)
val valueTextView: TextView = itemView.findViewById(R.id.result_count_text)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): ResultViewHolder {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.layout_result_row, parent, false)
return ResultViewHolder(view)
}
override fun onBindViewHolder(
holder: ResultViewHolder,
position: Int,
) {
val item = dataList[position]
holder.keyTextView.text = item.first
holder.valueTextView.text = item.second
}
override fun getItemCount(): Int {
return dataList.size
}
}
package com.k2_9.omrekap.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import com.k2_9.omrekap.R
class HomePageFragment : Fragment() {
private fun handleBackNavigation() {
activity?.finishAffinity()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
handleBackNavigation()
}
},
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home_page, container, false)
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?,
) {
super.onViewCreated(view, savedInstanceState)
}
}
package com.k2_9.omrekap.fragments
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.activity.OnBackPressedCallback
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.k2_9.omrekap.R
import com.k2_9.omrekap.activities.CameraActivity
import com.k2_9.omrekap.activities.ExpandImageActivity
import com.k2_9.omrekap.activities.MainActivity
import com.k2_9.omrekap.adapters.ResultAdapter
/**
* A simple [Fragment] subclass.
* Use the [ResultPageFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ResultPageFragment : Fragment() {
companion object {
const val ARG_NAME_IS_FROM_CAMERA = "IS_FROM_CAMERA"
const val ARG_NAME_IMAGE_URI_STRING = "IMAGE_URI_STRING"
}
private var isFromCamera: Boolean = false
private var imageUriString: String? = null
private lateinit var recyclerView: RecyclerView
private lateinit var resultAdapter: ResultAdapter
private fun onBackCamera() {
val intent = Intent(context, CameraActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOP)
activity?.finish()
startActivity(intent)
}
private fun onHomeButtonClick() {
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
activity?.finish()
startActivity(intent)
}
private fun handleBackNavigation() {
// TODO: CLEAR VIEWMODEL
if (isFromCamera) {
onBackCamera()
} else {
onHomeButtonClick()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Retrieve the arguments
val args = arguments
// Check if arguments are not null and retrieve values
if (args != null) {
isFromCamera = args.getBoolean(ARG_NAME_IS_FROM_CAMERA)
imageUriString = args.getString(ARG_NAME_IMAGE_URI_STRING)
if (imageUriString == null) {
throw IllegalArgumentException("Image URI string is null")
}
}
requireActivity().onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
handleBackNavigation()
}
},
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val view = inflater.inflate(R.layout.fragment_result_page, container, false)
// Initialize your data (list of key-value pairs)
val resultData =
listOf(
Pair("Prabowo Subianto Djojohadikusumo", "270,20 juta"),
Pair("Key2", "Value2"),
Pair("Key3", "Value3"),
Pair("Key4", "Value4"),
Pair("Key5", "Value5"),
Pair("Key6", "Value6"),
// ... add more key-value pairs as needed
)
// remove shadow
val resultCardView: CardView = view.findViewById(R.id.result_card_view)
val homeCardView: CardView = view.findViewById(R.id.home_card_view)
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
resultCardView.elevation = 0f
homeCardView.elevation = 0f
}
// Set up RecyclerView
recyclerView = view.findViewById(R.id.result_recycler_view)
recyclerView.layoutManager = LinearLayoutManager(requireContext())
resultAdapter = ResultAdapter(resultData)
recyclerView.adapter = resultAdapter
// link image URI with view
val documentImageView: ImageView = view.findViewById(R.id.document_image)
documentImageView.tag = imageUriString
Log.d("ResultPageFragment", "load image " + imageUriString.toString())
documentImageView.setImageURI(Uri.parse(imageUriString))
// remove progress bar
val progressLoader : ProgressBar = view.findViewById(R.id.progress_loader)
progressLoader.visibility = View.GONE
// configure expand action
val expandButton: ImageButton = view.findViewById(R.id.expand_button)
expandButton.setOnClickListener {
// Pass the image resource ID to ExpandImageActivity
val imageResource = documentImageView.tag ?: R.drawable.ic_image
val intent = Intent(requireContext(), ExpandImageActivity::class.java)
// Choose the appropriate constant based on the type of resource
when (imageResource) {
is Int -> {
intent.putExtra(ExpandImageActivity.EXTRA_NAME_DRAWABLE_RESOURCE, imageResource)
}
is Uri -> {
intent.putExtra(ExpandImageActivity.EXTRA_NAME_IMAGE_RESOURCE, imageResource.toString())
}
else -> {
throw IllegalArgumentException("Unsupported resource type")
}
}
startActivity(intent)
}
// set home button listener
val homeButton: ImageButton = view.findViewById(R.id.home_button)
homeButton.setOnClickListener {
onHomeButtonClick()
}
return view
}
}
package com.k2_9.omrekap.models
import android.net.Uri
data class ImageSaveData(val rawImage: Uri, var annotatedImage: Uri?, var data: Map<String, Int>?) {
fun isProcessed(): Boolean {
return annotatedImage != null && data != null
}
}
package com.k2_9.omrekap.utils
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import com.k2_9.omrekap.models.ImageSaveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileDescriptor
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class SaveHelper {
suspend fun save(
context: Context,
data: ImageSaveData,
) {
val folderName: String = generateFolderName()
if (data.rawImage.toString() == "") {
throw RuntimeException("The raw image URI is empty")
}
if (data.annotatedImage == null || data.data == null) {
throw RuntimeException("Image has not been processed yet")
}
val rawImageBitmap = uriToBitmap(context, data.rawImage)
val annotatedImageBitmap = uriToBitmap(context, data.annotatedImage!!)
withContext(Dispatchers.IO) {
saveImage(context, rawImageBitmap, folderName, "raw_image.jpg")
saveImage(context, annotatedImageBitmap, folderName, "annotated_image.jpg")
saveJSON(context, data.data!!, folderName, "data.json")
}
}
private fun uriToBitmap(
context: Context,
selectedFileUri: Uri,
): Bitmap {
val parcelFileDescriptor = context.contentResolver.openFileDescriptor(selectedFileUri, "r")
val fileDescriptor: FileDescriptor = parcelFileDescriptor!!.fileDescriptor
val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
parcelFileDescriptor.close()
return image
}
private fun generateFolderName(): String {
val sdf = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
return sdf.format(Date())
}
private fun saveImage(
context: Context,
image: Bitmap,
folderName: String,
fileName: String,
) {
// Save the image to the Documents/OMRekap/folderName directory
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
saveImageBeforeAndroidQ(image, folderName, fileName)
} else {
saveImageAndroidQandAbove(context, image, folderName, fileName)
}
}
private fun saveJSON(
context: Context,
data: Map<String, Int>,
folderName: String,
fileName: String,
) {
// Save the JSON to the Documents/OMRekap/folderName directory
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
saveJSONBeforeAndroidQ(data, folderName, fileName)
} else {
saveJSONAndroidQandAbove(context, data, folderName, fileName)
}
}
private fun saveImageBeforeAndroidQ(
image: Bitmap,
folderName: String,
fileName: String,
) {
// Save the image using the deprecated environment.getExternalStoragePublicDirectory() method
val documentDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val appDir = File(documentDir, "OMRekap")
val fileDir = File(appDir, folderName)
if (!fileDir.exists()) {
if (!fileDir.mkdirs()) {
throw RuntimeException("Failed to create directory: $fileDir")
}
}
val imageFile = File(fileDir, fileName)
val fileOutputStream = FileOutputStream(imageFile)
image.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
fileOutputStream.flush()
fileOutputStream.close()
}
@RequiresApi(Build.VERSION_CODES.Q)
private fun saveImageAndroidQandAbove(
context: Context,
image: Bitmap,
folderName: String,
fileName: String,
) {
// Save the image using the new MediaStore API
val contentValues =
ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + File.separator + "OMRekap" + File.separator + folderName)
}
val uri = context.contentResolver.insert(MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), contentValues)
if (uri != null) {
val stream = context.contentResolver.openOutputStream(uri)
if (stream != null) {
image.compress(Bitmap.CompressFormat.JPEG, 100, stream)
stream.close()
} else {
// TODO: Handle the case where the stream is null
}
} else {
// TODO: Handle the case where the uri is null
}
}
private fun saveJSONBeforeAndroidQ(
data: Map<String, Int>,
folderName: String,
fileName: String,
) {
// Save the JSON using the deprecated environment.getExternalStoragePublicDirectory() method
val documentDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val appDir = File(documentDir, "OMRekap")
val fileDir = File(appDir, folderName)
if (!fileDir.exists()) {
if (!fileDir.mkdirs()) {
throw RuntimeException("Failed to create directory: $fileDir")
}
}
val jsonFile = File(fileDir, fileName)
val fileOutputStream = FileOutputStream(jsonFile)
fileOutputStream.write(data.toString().toByteArray())
fileOutputStream.flush()
fileOutputStream.close()
}
@RequiresApi(Build.VERSION_CODES.Q)
private fun saveJSONAndroidQandAbove(
context: Context,
data: Map<String, Int>,
folderName: String,
fileName: String,
) {
// Save the JSON using the new MediaStore API
val contentValues =
ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "application/json")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + File.separator + "OMRekap" + File.separator + folderName)
}
val uri = context.contentResolver.insert(MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), contentValues)
if (uri != null) {
val stream = context.contentResolver.openOutputStream(uri)
if (stream != null) {
stream.write(data.toString().toByteArray())
stream.close()
} else {
// TODO: Handle the case where the stream is null
}
} else {
// TODO: Handle the case where the uri is null
}
}
}
package com.k2_9.omrekap.view_models
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.k2_9.omrekap.models.ImageSaveData
import kotlinx.coroutines.launch
class ImageDataViewModel : ViewModel() {
private val _data = MutableLiveData<ImageSaveData>()
val data = _data as LiveData<ImageSaveData>
fun processImage(image: Uri) {
viewModelScope.launch {
// TODO: Process the raw image using OMRHelper
val data = ImageSaveData(image, image, mapOf())
_data.value = data
}
}
}
This diff is collapsed.
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment