From d0ebae456692a82fa1f5c8f2dc8d6de5ccb62c51 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Tue, 19 Dec 2023 14:04:29 +0100 Subject: [PATCH] wip: reading file from either local or web need-to: parse a file - we may need to decide on a format? --- app/src/main/AndroidManifest.xml | 2 + .../memorisationapplication/HomeScreen.kt | 7 +++- .../ui/HomeViewModel.kt | 41 ++++++++++++++++++- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7766a47..e660465 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,8 @@ + + Unit, @@ -289,7 +292,7 @@ fun ImportDialog( confirmButton = { Button( // TODO : on charge le jeu de question dans le sujet - onClick = { model.import(lien) }, + onClick = { GlobalScope.launch { model.import(lien) } }, content = { Text("Importer") } ) }, diff --git a/app/src/main/java/fr/uparis/diamantkennel/memorisationapplication/ui/HomeViewModel.kt b/app/src/main/java/fr/uparis/diamantkennel/memorisationapplication/ui/HomeViewModel.kt index 858d26b..4ee868a 100644 --- a/app/src/main/java/fr/uparis/diamantkennel/memorisationapplication/ui/HomeViewModel.kt +++ b/app/src/main/java/fr/uparis/diamantkennel/memorisationapplication/ui/HomeViewModel.kt @@ -8,7 +8,14 @@ import androidx.lifecycle.viewModelScope import fr.uparis.diamantkennel.memorisationapplication.MemoApplication import fr.uparis.diamantkennel.memorisationapplication.data.SetQuestions import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch +import java.io.BufferedReader +import java.io.File +import java.io.InputStreamReader +import java.net.HttpURLConnection +import java.net.URL class HomeViewModel(application: Application) : AndroidViewModel(application) { private val dao = (application as MemoApplication).database.memoDao() @@ -129,7 +136,39 @@ class HomeViewModel(application: Application) : AndroidViewModel(application) { error.value = null } - fun import(path: String) { + suspend fun import(path: String) { + val data = + flow { + if (path.startsWith("content://")) { + // Local file + val bufferedReader: BufferedReader = File(path).bufferedReader() + + emit(bufferedReader.use { it.readText() }) + } else { + // File from internet + val url = URL(path) + val connection = url.openConnection() as HttpURLConnection + connection.requestMethod = "GET" + + val inputStream = connection.inputStream + val reader = BufferedReader(InputStreamReader(inputStream)) + + var content = "" + var line: String? = reader.readLine() + while (line != null) { + content += line + line = reader.readLine() + } + + connection.disconnect() + + emit(content) + } + }.flowOn(Dispatchers.IO) + dismissImportation() + + // `data` + // Correspond au contenu du fichier qu'il faut ajouter à la bdd } }