added database feature, to check entries

This commit is contained in:
oxidiert
2025-09-08 13:04:37 +02:00
parent 650a3bb050
commit 0dfc5df878
7 changed files with 502 additions and 29 deletions

View File

@ -28,6 +28,9 @@ interface QuestionnaireDao {
@Query("SELECT * FROM questionnaires WHERE id = :id LIMIT 1")
suspend fun getById(id: String): Questionnaire?
@Query("SELECT * FROM questionnaires")
suspend fun getAll(): List<Questionnaire> // <-- NEU
}
@Dao

View File

@ -0,0 +1,279 @@
package com.dano.test1
import android.util.Log
import android.view.View
import android.widget.*
import com.dano.test1.data.Client
import com.dano.test1.data.CompletedQuestionnaire
import com.dano.test1.data.Question
import com.dano.test1.data.Questionnaire
import kotlinx.coroutines.*
import kotlin.math.roundToInt
import com.dano.test1.R
class DatabaseButtonHandler(
private val activity: MainActivity,
private val databaseButton: Button,
private val onClose: () -> Unit
) {
private val uiScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val tag = "DatabaseButtonHandler"
fun setup() {
databaseButton.text = "Datenbank"
databaseButton.setOnClickListener { openDatabaseScreen() }
}
// ---------------------------
// SCREEN 1: Client-Liste
// ---------------------------
private fun openDatabaseScreen() {
activity.setContentView(R.layout.database_screen)
val table: TableLayout = requireView(R.id.tableClients, "tableClients")
val progress: ProgressBar = requireView(R.id.progressBar, "progressBar")
val emptyView: TextView = requireView(R.id.emptyView, "emptyView")
val backButton: Button = requireView(R.id.backButton, "backButton")
backButton.setOnClickListener { onClose() }
progress.visibility = View.VISIBLE
emptyView.visibility = View.GONE
table.removeAllViews()
addHeaderRow(table, listOf("#", "Client-Code"))
uiScope.launch {
val clients: List<Client> = withContext(Dispatchers.IO) {
MyApp.database.clientDao().getAllClients()
}
progress.visibility = View.GONE
if (clients.isEmpty()) {
emptyView.visibility = View.VISIBLE
return@launch
}
clients.forEachIndexed { index, client ->
addClickableRow(
table = table,
cells = listOf((index + 1).toString(), client.clientCode),
onClick = { openClientOverviewScreen(client.clientCode) }
)
}
}
}
// ---------------------------
// SCREEN 2: Fragebogen-Übersicht für einen Client
// ---------------------------
private fun openClientOverviewScreen(clientCode: String) {
activity.setContentView(R.layout.client_overview_screen)
val title: TextView = requireView(R.id.titleClientOverview, "titleClientOverview")
val table: TableLayout = requireView(R.id.tableQuestionnaires, "tableQuestionnaires")
val progress: ProgressBar = requireView(R.id.progressBarClient, "progressBarClient")
val emptyView: TextView = requireView(R.id.emptyViewClient, "emptyViewClient")
val backButton: Button = requireView(R.id.backButtonClient, "backButtonClient")
title.text = "Client: $clientCode Fragebögen"
backButton.setOnClickListener { openDatabaseScreen() }
progress.visibility = View.VISIBLE
emptyView.visibility = View.GONE
table.removeAllViews()
addHeaderRow(table, listOf("#", "Fragebogen-ID", "Status"))
uiScope.launch {
val (allQuestionnaires, completedForClient) = withContext(Dispatchers.IO) {
val qs = MyApp.database.questionnaireDao().getAll()
val done = MyApp.database.completedQuestionnaireDao().getAllForClient(clientCode)
qs to done
}
progress.visibility = View.GONE
if (allQuestionnaires.isEmpty()) {
emptyView.text = "Keine Fragebögen vorhanden."
emptyView.visibility = View.VISIBLE
return@launch
}
val statusMap = completedForClient.associate { it.questionnaireId to it.isDone }
allQuestionnaires.forEachIndexed { idx, q ->
val isDone = statusMap[q.id] ?: false
val statusText = if (isDone) "" else ""
val statusColor = if (isDone) 0xFF4CAF50.toInt() else 0xFFF44336.toInt()
if (isDone) {
// NUR diese sind klickbar
addClickableRow(
table = table,
cells = listOf((idx + 1).toString(), q.id, statusText),
onClick = { openQuestionnaireDetailScreen(clientCode, q.id) },
colorOverrides = mapOf(2 to statusColor)
)
} else {
// Nicht klickbar, leicht ausgegraut
addDisabledRow(
table = table,
cells = listOf((idx + 1).toString(), q.id, statusText),
colorOverrides = mapOf(2 to statusColor)
)
}
}
}
}
// ---------------------------
// SCREEN 3: Fragen & Antworten zu einem Fragebogen
// ---------------------------
private fun openQuestionnaireDetailScreen(clientCode: String, questionnaireId: String) {
activity.setContentView(R.layout.questionnaire_detail_screen)
val title: TextView = requireView(R.id.titleQuestionnaireDetail, "titleQuestionnaireDetail")
val table: TableLayout = requireView(R.id.tableQA, "tableQA")
val progress: ProgressBar = requireView(R.id.progressBarQA, "progressBarQA")
val emptyView: TextView = requireView(R.id.emptyViewQA, "emptyViewQA")
val backButton: Button = requireView(R.id.backButtonQA, "backButtonQA")
title.text = "Client: $clientCode Fragebogen: $questionnaireId"
backButton.setOnClickListener { openClientOverviewScreen(clientCode) }
progress.visibility = View.VISIBLE
emptyView.visibility = View.GONE
table.removeAllViews()
addHeaderRow(table, listOf("#", "Frage", "Antwort"))
uiScope.launch {
val (questions, answersForClient) = withContext(Dispatchers.IO) {
val qs = MyApp.database.questionDao().getQuestionsForQuestionnaire(questionnaireId)
val ans = MyApp.database.answerDao()
.getAnswersForClientAndQuestionnaire(clientCode, questionnaireId)
qs to ans
}
progress.visibility = View.GONE
if (questions.isEmpty()) {
emptyView.text = "Keine Fragen vorhanden."
emptyView.visibility = View.VISIBLE
return@launch
}
val answerMap = answersForClient.associate { it.questionId to it.answerValue }
questions.forEachIndexed { idx, q: Question ->
val qText = q.question.takeIf { it.isNotBlank() } ?: q.questionId
val aText = answerMap[q.questionId]?.takeIf { it.isNotBlank() } ?: ""
addRow(table, listOf((idx + 1).toString(), qText, aText))
}
}
}
// ---------------------------
// UI-Helfer
// ---------------------------
private fun addHeaderRow(table: TableLayout, labels: List<String>) {
val row = TableRow(activity)
labels.forEach { label -> row.addView(makeHeaderCell(label)) }
table.addView(row)
addDivider(table)
}
private fun addRow(
table: TableLayout,
cells: List<String>,
colorOverrides: Map<Int, Int> = emptyMap()
) {
val row = TableRow(activity)
cells.forEachIndexed { index, text ->
row.addView(makeBodyCell(text, colorOverrides[index]))
}
table.addView(row)
addDivider(table)
}
private fun addClickableRow(
table: TableLayout,
cells: List<String>,
onClick: () -> Unit,
colorOverrides: Map<Int, Int> = emptyMap()
) {
val row = TableRow(activity).apply {
isClickable = true
isFocusable = true
setBackgroundResource(android.R.drawable.list_selector_background)
setOnClickListener { onClick() }
}
cells.forEachIndexed { index, text ->
row.addView(makeBodyCell(text, colorOverrides[index]))
}
table.addView(row)
addDivider(table)
}
private fun addDisabledRow(
table: TableLayout,
cells: List<String>,
colorOverrides: Map<Int, Int> = emptyMap()
) {
val row = TableRow(activity).apply {
isClickable = false
isEnabled = false
alpha = 0.6f // leicht ausgegraut
}
cells.forEachIndexed { index, text ->
row.addView(makeBodyCell(text, colorOverrides[index]))
}
table.addView(row)
addDivider(table)
}
private fun addDivider(table: TableLayout) {
val divider = View(activity)
val params = TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
dp(1)
)
divider.layoutParams = params
divider.setBackgroundColor(0xFFDDDDDD.toInt())
table.addView(divider)
}
private fun makeHeaderCell(text: String): TextView =
TextView(activity).apply {
this.text = text
setPadding(dp(12), dp(10), dp(12), dp(10))
textSize = 16f
setTypeface(typeface, android.graphics.Typeface.BOLD)
}
private fun makeBodyCell(text: String, color: Int? = null): TextView =
TextView(activity).apply {
this.text = text
setPadding(dp(12), dp(10), dp(12), dp(10))
textSize = 15f
color?.let { setTextColor(it) }
}
private fun dp(value: Int): Int {
val density = activity.resources.displayMetrics.density
return (value * density).roundToInt()
}
private fun <T : View> requireView(id: Int, name: String): T {
val v = activity.findViewById<T>(id)
if (v == null) {
val msg = "View with id '$name' not found in current layout."
Log.e(tag, msg)
Toast.makeText(activity, "Fehlende View: $name", Toast.LENGTH_LONG).show()
throw IllegalStateException(msg)
}
return v
}
}

View File

@ -22,6 +22,7 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
private lateinit var editButton: Button
private lateinit var uploadButton: Button
private lateinit var downloadButton: Button
private lateinit var databaseButton: Button // <-- NEU
private val dynamicButtons = mutableListOf<Button>()
private val questionnaireFiles = mutableMapOf<Button, String>()
@ -43,6 +44,7 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
setupEditButtonHandler()
setupUploadButton()
setupDownloadButton()
setupDatabaseButtonHandler() // <-- NEU
val dbPath = "/data/data/com.dano.test1/databases/questionnaire_database"
val pathExists = File(dbPath).exists()
@ -63,6 +65,7 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
editButton = activity.findViewById(R.id.editButton)
uploadButton = activity.findViewById(R.id.uploadButton)
downloadButton = activity.findViewById(R.id.downloadButton)
databaseButton = activity.findViewById(R.id.databaseButton) // <-- NEU
val tag = editText.tag as? String ?: ""
editText.hint = LanguageManager.getText(languageID, tag)
@ -90,7 +93,6 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
}
}
// Parser: erzeugt ein QuestionItem.Condition? (sehr robust gegenüber verschiedenen JSON-Formaten)
private fun parseCondition(conditionObj: JSONObject?): QuestionItem.Condition? {
if (conditionObj == null) return null
if (conditionObj.has("anyOf")) {
@ -163,17 +165,13 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
dynamicButtons.forEach { button ->
button.setOnClickListener {
// Optional: LAST_CLIENT_CODE synchronisieren (rein informativ)
GlobalValues.LAST_CLIENT_CODE = GlobalValues.LOADED_CLIENT_CODE
startQuestionnaireForButton(button)
setButtonsEnabled(dynamicButtons.filter { it == button })
}
}
}
private fun restorePreviousClientCode() {
GlobalValues.LAST_CLIENT_CODE?.let { editText.setText(it) }
}
@ -213,13 +211,9 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
private fun updateButtonTexts() {
questionnaireFiles.forEach { (button, fileName) ->
val entry = questionnaireEntries.firstOrNull { it.file == fileName }
// key ableiten
val key = fileName.substringAfter("questionnaire_").substringAfter("_").removeSuffix(".json")
var buttonText = LanguageManager.getText(languageID, key)
val pointsAvailable = buttonPoints.entries.firstOrNull { fileName.contains(it.key, ignoreCase = true) }
val points = pointsAvailable?.value ?: 0
@ -231,10 +225,10 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
if (entry?.showPoints == true && pointsAvailable != null) {
when {
points in 0..12 -> button.setBackgroundColor(Color.parseColor("#4CAF50")) // Grün
points in 13..36 -> button.setBackgroundColor(Color.parseColor("#FFEB3B")) // Gelb
points in 37..100 -> button.setBackgroundColor(Color.parseColor("#F44336")) // Rot
else -> button.setBackgroundColor(Color.parseColor("#E0E0E0")) // Grau bei 0 Punkten
points in 0..12 -> button.setBackgroundColor(Color.parseColor("#4CAF50"))
points in 13..36 -> button.setBackgroundColor(Color.parseColor("#FFEB3B"))
points in 37..100 -> button.setBackgroundColor(Color.parseColor("#F44336"))
else -> button.setBackgroundColor(Color.parseColor("#E0E0E0"))
}
} else {
button.setBackgroundColor(Color.parseColor("#E0E0E0"))
@ -242,6 +236,7 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
}
buttonLoad.text = LanguageManager.getText(languageID, "load")
databaseButton.text = "Datenbank" // fixierter Text gewünscht
}
private fun setButtonsEnabled(enabledButtons: List<Button>) {
@ -282,12 +277,10 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
buttonPoints = buttonPoints,
updateButtonTexts = { updateButtonTexts() },
setButtonsEnabled = { setButtonsEnabled(it) },
// Vor "Bearbeiten" ggf. den Load-Button ausführen
triggerLoad = { buttonLoad.performClick() }
).setup()
}
private fun setupUploadButton() {
uploadButton.text = "Upload"
uploadButton.setOnClickListener {
@ -295,10 +288,7 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
GlobalValues.LAST_CLIENT_CODE = clientCode
// Passwort-Eingabe-Popup
val input = EditText(activity).apply {
hint = "Server-Passwort"
}
val input = EditText(activity).apply { hint = "Server-Passwort" }
android.app.AlertDialog.Builder(activity)
.setTitle("Login erforderlich")
@ -307,7 +297,6 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
val password = input.text.toString()
if (password.isNotBlank()) {
Toast.makeText(activity, "Login wird überprüft...", Toast.LENGTH_SHORT).show()
// Login + Upload starten
DatabaseUploader.uploadDatabaseWithLogin(activity, password)
} else {
Toast.makeText(activity, "Bitte Passwort eingeben", Toast.LENGTH_SHORT).show()
@ -324,10 +313,7 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
val clientCode = editText.text.toString().trim()
GlobalValues.LAST_CLIENT_CODE = clientCode
// Eingabe-Popup für Passwort anzeigen
val input = EditText(activity).apply {
hint = "Server-Passwort"
}
val input = EditText(activity).apply { hint = "Server-Passwort" }
android.app.AlertDialog.Builder(activity)
.setTitle("Login erforderlich")
@ -335,7 +321,6 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
.setPositiveButton("OK") { _, _ ->
val password = input.text.toString()
if (password.isNotBlank()) {
// Login starten
LoginManager.loginUser(
context = activity,
password = password,
@ -357,8 +342,18 @@ class HandlerOpeningScreen(private val activity: MainActivity) {
}
}
private fun setupDatabaseButtonHandler() {
DatabaseButtonHandler(
activity = activity,
databaseButton = databaseButton
) {
// zurück zum Opening-Screen
init()
}.setup()
}
private fun updateMainButtonsState(isDatabaseAvailable: Boolean) {
val buttons = listOf(buttonLoad, saveButton, editButton)
val buttons = listOf(buttonLoad, saveButton, editButton, databaseButton) // <-- NEU dabei
buttons.forEach { button ->
button.isEnabled = isDatabaseAvailable
button.alpha = if (isDatabaseAvailable) 1.0f else 0.5f

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootClientOverview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/titleClientOverview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Client Fragebögen"
android:textStyle="bold"
android:textSize="20sp"
android:paddingBottom="8dp" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true"
android:scrollbars="horizontal">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="vertical">
<TableLayout
android:id="@+id/tableQuestionnaires"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="1" />
</ScrollView>
</HorizontalScrollView>
<TextView
android:id="@+id/emptyViewClient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Keine Daten."
android:visibility="gone"
android:paddingTop="8dp" />
<ProgressBar
android:id="@+id/progressBarClient"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="8dp"
android:paddingBottom="8dp" />
<Button
android:id="@+id/backButtonClient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Zurück" />
</LinearLayout>

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootDatabase"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Datenbank Clients"
android:textStyle="bold"
android:textSize="20sp"
android:paddingBottom="8dp" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true"
android:scrollbars="horizontal">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="vertical">
<TableLayout
android:id="@+id/tableClients"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="1" />
</ScrollView>
</HorizontalScrollView>
<TextView
android:id="@+id/emptyView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Keine Clients vorhanden."
android:visibility="gone"
android:paddingTop="8dp" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="8dp"
android:paddingBottom="8dp" />
<Button
android:id="@+id/backButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Zurück" />
</LinearLayout>

View File

@ -2,6 +2,7 @@
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
@ -71,6 +72,15 @@
app:layout_constraintStart_toStartOf="@id/editText"
app:layout_constraintTop_toBottomOf="@id/editText" />
<Button
android:id="@+id/databaseButton"
android:layout_width="200dp"
android:layout_height="42dp"
android:layout_marginTop="132dp"
app:layout_constraintEnd_toEndOf="@id/editText"
app:layout_constraintStart_toStartOf="@id/editText"
app:layout_constraintTop_toBottomOf="@id/editText" />
<Button
android:id="@+id/editButton"
android:layout_width="72dp"
@ -90,13 +100,13 @@
<TextView
android:id="@+id/textView"
android:layout_width="348dp"
android:layout_height="162dp"
android:layout_width="333dp"
android:layout_height="81dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.492"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.307" />
app:layout_constraintVertical_bias="0.514" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootQuestionnaireDetail"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/titleQuestionnaireDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragen und Antworten"
android:textStyle="bold"
android:textSize="20sp"
android:paddingBottom="8dp" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true"
android:scrollbars="horizontal">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="vertical">
<TableLayout
android:id="@+id/tableQA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stretchColumns="1,2" />
</ScrollView>
</HorizontalScrollView>
<TextView
android:id="@+id/emptyViewQA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Keine Fragen vorhanden."
android:visibility="gone"
android:paddingTop="8dp" />
<ProgressBar
android:id="@+id/progressBarQA"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="8dp"
android:paddingBottom="8dp" />
<Button
android:id="@+id/backButtonQA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Zurück" />
</LinearLayout>