Commit 533a542b by Paktalin

Wordlist is saved on pause or when modifications reach MAX_PERMITTED size

parent 61f93aaf
package com.paktalin.vocabularynotebook.firestoreitems
enum class ModifiedLabel {
ADDED, UPDATED, DELETED
}
\ No newline at end of file
...@@ -5,6 +5,7 @@ import java.util.Date ...@@ -5,6 +5,7 @@ import java.util.Date
class WordItem(word: String, translation: String, time: Date?, var id: String?, private val vocabularyId: String?) : Serializable { class WordItem(word: String, translation: String, time: Date?, var id: String?, private val vocabularyId: String?) : Serializable {
var pojo: Pojo = Pojo(word, translation, time) var pojo: Pojo = Pojo(word, translation, time)
var modifiedLabel: ModifiedLabel? = null
class Pojo(var word: String, var translation: String, var time:Date? = null) : Serializable { class Pojo(var word: String, var translation: String, var time:Date? = null) : Serializable {
init { init {
......
...@@ -10,16 +10,16 @@ import android.view.View ...@@ -10,16 +10,16 @@ import android.view.View
import android.view.WindowManager import android.view.WindowManager
import android.view.inputmethod.InputMethodManager import android.view.inputmethod.InputMethodManager
import com.paktalin.vocabularynotebook.R import com.paktalin.vocabularynotebook.R
import com.paktalin.vocabularynotebook.Vocabulary import com.paktalin.vocabularynotebook.vocabulary.Vocabulary
import com.paktalin.vocabularynotebook.Vocabulary.Companion.SORT_BY_TIME import com.paktalin.vocabularynotebook.vocabulary.Vocabulary.Companion.SORT_BY_TIME
import com.paktalin.vocabularynotebook.Vocabulary.Companion.SORT_BY_TRANSLATION import com.paktalin.vocabularynotebook.vocabulary.Vocabulary.Companion.SORT_BY_TRANSLATION
import com.paktalin.vocabularynotebook.Vocabulary.Companion.SORT_BY_WORD import com.paktalin.vocabularynotebook.vocabulary.Vocabulary.Companion.SORT_BY_WORD
import com.paktalin.vocabularynotebook.VocabularyAdapter import com.paktalin.vocabularynotebook.vocabulary.VocabularyAdapter
import com.paktalin.vocabularynotebook.firestoreitems.WordItem
import com.paktalin.vocabularynotebook.ui.views.LockableLayoutManager import com.paktalin.vocabularynotebook.ui.views.LockableLayoutManager
import com.paktalin.vocabularynotebook.utils.* import com.paktalin.vocabularynotebook.utils.*
import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.* import kotlinx.android.synthetic.main.content_main.*
import java.lang.Exception
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
...@@ -86,10 +86,10 @@ class MainActivity : AppCompatActivity() { ...@@ -86,10 +86,10 @@ class MainActivity : AppCompatActivity() {
FirestoreManager().extractVocabularyId({ FirestoreManager().extractVocabularyId({
// recyclerView.adapter = VocabularyAdapter(Vocabulary(), this@MainActivity) // recyclerView.adapter = VocabularyAdapter(Vocabulary(), this@MainActivity)
recyclerView.layoutManager = LockableLayoutManager(this@MainActivity) recyclerView.layoutManager = LockableLayoutManager(this@MainActivity)
FirestoreManager().extractVocabulary { documents -> FirestoreManager().extractVocabulary { querySnapshot ->
run { run {
if (documents.isNotEmpty()) { if (querySnapshot != null && !querySnapshot.isEmpty) {
vocabularyAdapter = VocabularyAdapter(Vocabulary.createFromDocs(documents), this@MainActivity) vocabularyAdapter = VocabularyAdapter(Vocabulary.createFromSnapshot(querySnapshot), this@MainActivity)
recyclerView.adapter = vocabularyAdapter recyclerView.adapter = vocabularyAdapter
} }
else showToastNoWords() else showToastNoWords()
...@@ -119,8 +119,10 @@ class MainActivity : AppCompatActivity() { ...@@ -119,8 +119,10 @@ class MainActivity : AppCompatActivity() {
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
// TODO save changes
hideKeyboard() hideKeyboard()
try {
FirestoreManager().saveWords(vocabularyAdapter.getModifiedWords())
} catch (ignored: Exception) {}
} }
companion object { companion object {
......
...@@ -3,11 +3,9 @@ package com.paktalin.vocabularynotebook.utils ...@@ -3,11 +3,9 @@ package com.paktalin.vocabularynotebook.utils
import android.content.Context import android.content.Context
import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.*
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import com.paktalin.vocabularynotebook.appsetup.ConfiguredFirestore import com.paktalin.vocabularynotebook.appsetup.ConfiguredFirestore
import com.paktalin.vocabularynotebook.firestoreitems.ModifiedLabel
import com.paktalin.vocabularynotebook.firestoreitems.UserPojo import com.paktalin.vocabularynotebook.firestoreitems.UserPojo
import com.paktalin.vocabularynotebook.firestoreitems.VocabularyPojo import com.paktalin.vocabularynotebook.firestoreitems.VocabularyPojo
import com.paktalin.vocabularynotebook.firestoreitems.WordItem import com.paktalin.vocabularynotebook.firestoreitems.WordItem
...@@ -61,6 +59,22 @@ class FirestoreManager { ...@@ -61,6 +59,22 @@ class FirestoreManager {
onFailure() } onFailure() }
} }
fun saveWords(wordList: MutableSet<WordItem>) {
if (wordList.isEmpty())
return
val batch = db.batch()
wordList.forEach { w -> kotlin.run {
Log.d(TAG, "${w.pojo.word} ${w.pojo.translation} ${w.id} ${w.modifiedLabel}")
if (w.modifiedLabel == ModifiedLabel.DELETED)
batch.delete(vocabularyDocument().collection(WORDS).document(w.id!!))
else if (w.modifiedLabel == ModifiedLabel.UPDATED && w.id != null)
batch.set(vocabularyDocument().collection(WORDS).document(w.id!!), w.pojo)
else
batch.set(vocabularyDocument().collection(WORDS).document(), w.pojo)
}}
batch.commit().addOnCompleteListener { Log.d(TAG, "words successfully updated") }
}
fun updateWord(onSuccess: () -> Unit, onFailure: () -> Unit, wordItem: WordItem, wordPojo: WordItem.Pojo) { fun updateWord(onSuccess: () -> Unit, onFailure: () -> Unit, wordItem: WordItem, wordPojo: WordItem.Pojo) {
vocabularyDocument() vocabularyDocument()
.collection(WORDS).document(wordItem.id!!).set(wordPojo) .collection(WORDS).document(wordItem.id!!).set(wordPojo)
...@@ -81,11 +95,11 @@ class FirestoreManager { ...@@ -81,11 +95,11 @@ class FirestoreManager {
.addOnFailureListener { e -> Log.w(TAG, "deleteWordWithId $id:failure", e.fillInStackTrace()) } .addOnFailureListener { e -> Log.w(TAG, "deleteWordWithId $id:failure", e.fillInStackTrace()) }
} }
fun extractVocabulary(onSuccess: (documents: MutableList<DocumentSnapshot>) -> Unit) { fun extractVocabulary(onComplete: (querySnapshot: QuerySnapshot?) -> Unit) {
vocabularyDocument().collection(WORDS) vocabularyDocument().collection(WORDS)
.orderBy("time", Query.Direction.DESCENDING) .orderBy("time", Query.Direction.DESCENDING)
.get() .get()
.addOnSuccessListener { onSuccess(it.documents)} .addOnCompleteListener { t -> onComplete(t.result) }
} }
private fun setNewUserWithVocabularyData(firebaseUser: FirebaseUser, private fun setNewUserWithVocabularyData(firebaseUser: FirebaseUser,
......
package com.paktalin.vocabularynotebook.vocabulary
import com.paktalin.vocabularynotebook.firestoreitems.ModifiedLabel
import com.paktalin.vocabularynotebook.firestoreitems.WordItem
import com.paktalin.vocabularynotebook.utils.FirestoreManager
private const val MAX_PERMITTED = 9
class ModifiedWords {
private var modified = mutableSetOf<WordItem>()
fun add(wordItem: WordItem, modifiedLabel: ModifiedLabel) {
wordItem.modifiedLabel = modifiedLabel
modified.add(wordItem)
if (modified.size == MAX_PERMITTED) {
FirestoreManager().saveWords(modified)
modified.clear()
}
}
fun get(): MutableSet<WordItem> {
return modified
}
}
package com.paktalin.vocabularynotebook package com.paktalin.vocabularynotebook.vocabulary
import android.support.v7.widget.SearchView import android.support.v7.widget.SearchView
......
package com.paktalin.vocabularynotebook package com.paktalin.vocabularynotebook.vocabulary
import android.support.v7.widget.RecyclerView import android.support.v7.widget.RecyclerView
import android.view.View import android.view.View
......
package com.paktalin.vocabularynotebook package com.paktalin.vocabularynotebook.vocabulary
import android.util.Log
import com.google.firebase.Timestamp import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.QuerySnapshot
import com.paktalin.vocabularynotebook.firestoreitems.ModifiedLabel
import com.paktalin.vocabularynotebook.firestoreitems.WordItem import com.paktalin.vocabularynotebook.firestoreitems.WordItem
import com.paktalin.vocabularynotebook.utils.FirestoreManager.Companion.vocabularyId import com.paktalin.vocabularynotebook.utils.FirestoreManager.Companion.vocabularyId
import com.paktalin.vocabularynotebook.utils.Log
class Vocabulary() { class Vocabulary() {
private var allWords: MutableList<WordItem> = mutableListOf() private var allWords = mutableListOf<WordItem>()
private var displayed: MutableList<WordItem> = mutableListOf() private var displayed = mutableListOf<WordItem>()
internal var modified = ModifiedWords()
companion object { companion object {
private val TAG = "VN/" + Vocabulary::class.java.simpleName private val TAG = "VN/" + Vocabulary::class.java.simpleName
...@@ -17,14 +19,15 @@ class Vocabulary() { ...@@ -17,14 +19,15 @@ class Vocabulary() {
const val SORT_BY_WORD = 1 const val SORT_BY_WORD = 1
const val SORT_BY_TRANSLATION = 2 const val SORT_BY_TRANSLATION = 2
fun createFromDocs(documents: MutableList<DocumentSnapshot>): Vocabulary { fun createFromSnapshot(querySnapshot: QuerySnapshot): Vocabulary {
val wordsFromDocs = mutableListOf<WordItem>() val wordsFromDocs = mutableListOf<WordItem>()
documents.forEach { ref -> querySnapshot.forEach { snapshot ->
Log.d(TAG, "extracting ${snapshot["word"]} ${snapshot["translation"]} ${snapshot.id}")
wordsFromDocs.add(WordItem( wordsFromDocs.add(WordItem(
ref["word"].toString(), snapshot["word"].toString(),
ref["translation"].toString(), snapshot["translation"].toString(),
(ref["time"] as Timestamp).toDate(), (snapshot["time"] as Timestamp).toDate(),
ref.id, vocabularyId!!)) snapshot.id, vocabularyId!!))
} }
return Vocabulary(wordsFromDocs) return Vocabulary(wordsFromDocs)
} }
...@@ -47,14 +50,19 @@ class Vocabulary() { ...@@ -47,14 +50,19 @@ class Vocabulary() {
fun deleteWord(wordItem: WordItem) { fun deleteWord(wordItem: WordItem) {
allWords.remove(wordItem) allWords.remove(wordItem)
displayed.remove(wordItem) displayed.remove(wordItem)
modified.add(wordItem, ModifiedLabel.DELETED)
} }
fun addWord(newWord: WordItem) { fun addWord(newWord: WordItem) {
Log.d(TAG, "vocabulary addWord")
allWords.add(0, newWord) allWords.add(0, newWord)
displayed.add(0, newWord) displayed.add(0, newWord)
displayed.forEach { w -> Log.d(TAG, w.toString()) } modified.add(newWord, ModifiedLabel.ADDED)
}
fun updateWord(updatedWord: WordItem) {
allWords[allWords.indexOf(updatedWord)] = updatedWord
displayed[displayed.indexOf(updatedWord)] = updatedWord
modified.add(updatedWord, ModifiedLabel.UPDATED)
} }
fun displayAll() { fun displayAll() {
...@@ -65,11 +73,6 @@ class Vocabulary() { ...@@ -65,11 +73,6 @@ class Vocabulary() {
allWords.filter { wordItem -> wordItem.contains(query) }.toCollection(displayed) allWords.filter { wordItem -> wordItem.contains(query) }.toCollection(displayed)
} }
fun updateWord(updatedWord: WordItem) {
allWords[allWords.indexOf(updatedWord)] = updatedWord
displayed[displayed.indexOf(updatedWord)] = updatedWord
}
fun displayedAt(position: Int): WordItem { fun displayedAt(position: Int): WordItem {
return displayed[position] return displayed[position]
} }
......
package com.paktalin.vocabularynotebook package com.paktalin.vocabularynotebook.vocabulary
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.os.Build import android.os.Build
...@@ -6,6 +6,7 @@ import android.os.Bundle ...@@ -6,6 +6,7 @@ import android.os.Bundle
import android.support.v7.widget.PopupMenu import android.support.v7.widget.PopupMenu
import android.support.v7.widget.RecyclerView import android.support.v7.widget.RecyclerView
import android.view.* import android.view.*
import com.paktalin.vocabularynotebook.R
import com.paktalin.vocabularynotebook.firestoreitems.WordItem import com.paktalin.vocabularynotebook.firestoreitems.WordItem
import com.paktalin.vocabularynotebook.ui.fragments.EditWordFragment import com.paktalin.vocabularynotebook.ui.fragments.EditWordFragment
import com.paktalin.vocabularynotebook.ui.activities.MainActivity import com.paktalin.vocabularynotebook.ui.activities.MainActivity
...@@ -108,6 +109,10 @@ class VocabularyAdapter(private val vocabulary: Vocabulary, private val mainActi ...@@ -108,6 +109,10 @@ class VocabularyAdapter(private val vocabulary: Vocabulary, private val mainActi
notifyDataSetChanged() notifyDataSetChanged()
} }
fun getModifiedWords(): MutableSet<WordItem> {
return vocabulary.modified.get()
}
companion object { companion object {
private val TAG = "VN/" + VocabularyAdapter::class.java.simpleName private val TAG = "VN/" + VocabularyAdapter::class.java.simpleName
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment