Commit 36c1dfbf by Paktalin

Added refresh by swipe

parent 0f261e01
......@@ -8,10 +8,11 @@ import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.LinearLayout
import android.widget.TextView
import com.paktalin.vocabularynotebook.firestoreitems.Vocabulary
import com.google.firebase.Timestamp
import com.paktalin.vocabularynotebook.firestoreitems.WordItem
import com.paktalin.vocabularynotebook.ui.fragments.EditWordFragment
import com.paktalin.vocabularynotebook.ui.activities.MainActivity
import com.paktalin.vocabularynotebook.utils.FirestoreManager
import com.paktalin.vocabularynotebook.utils.addFragment
import kotlinx.android.synthetic.main.word_item.view.*
......@@ -74,6 +75,14 @@ class VocabularyAdapter(private val displayedVocabulary: Vocabulary, private val
this.notifyItemRangeChanged(position, displayedVocabulary.size())
}
fun updateAll() {
displayedVocabulary.clear()
FirestoreManager().retrieveWordsData { documents ->
displayedVocabulary.addWordsAsDocuments(documents)
this.notifyDataSetChanged()
}
}
fun addWord(newWord: WordItem) {
displayedVocabulary.addWord(newWord)
this.sort()
......
package com.paktalin.vocabularynotebook.firestoreitems
class Vocabulary(words: MutableList<WordItem>) {
companion object {
private val TAG = "VN/" + Vocabulary::class.java.simpleName
private const val SORT_BY_TIME = 0
private const val SORT_BY_WORD = 1
private const val SORT_BY_TRANSLATION = 2
}
var pojo:Pojo
private var words: MutableList<WordItem>
class Pojo(var title:String?) {
init {
if (title == null) title = "Untitled vocabulary"
}
}
init {
this.pojo = Pojo(null)
this.words = words
}
fun sort(sortOrder:Int) {
when(sortOrder) {
SORT_BY_TIME -> sortByTime()
SORT_BY_WORD -> sortByWord()
SORT_BY_TRANSLATION -> sortByTranslation()
}
}
fun deleteWord(position:Int) {
words[position].delete() // delete word from the database
words.removeAt(position) // delete word from the list
}
fun addWord(newWord:WordItem) {
words.add(0, newWord)
}
fun addWords(newWords:MutableList<WordItem>) {
words.addAll(newWords)
}
fun addWordsFittingQuery(newWords:MutableList<WordItem>, query:String) {
for (newWord in newWords) {
if (newWord.contains(query))
this.addWord(newWord)
}
}
fun updateWord(updatedWord:WordItem) {
val updatedItemIndex = words.indexOf(updatedWord)
words[updatedItemIndex] = updatedWord
}
fun getAt(position: Int):WordItem {
return words[position]
}
fun get():MutableList<WordItem> { return words }
fun size():Int { return words.size }
fun clear() { words.clear() }
private fun sortByTime() {
words.sortWith(Comparator { item1, item2 ->
-item1.pojo.time!!.compareTo(item2.pojo.time) })
}
private fun sortByWord() {
words.sortWith(Comparator { item1, item2 ->
item1.pojo.word.compareTo(item2.pojo.word) })
}
private fun sortByTranslation() {
words.sortWith(Comparator { item1, item2 ->
item1.pojo.translation.compareTo(item2.pojo.translation) })
}
}
\ No newline at end of file
package com.paktalin.vocabularynotebook.firestoreitems
class VocabularyPojo(var title:String?) {
init {
if (title == null) title = "Untitled vocabulary"
}
}
......@@ -11,10 +11,12 @@ import android.view.View
import android.view.inputmethod.InputMethodManager
import kotlinx.android.synthetic.main.fragment_vocabulary.*
import android.support.v7.widget.SearchView
import android.util.Log
import android.view.WindowManager
import com.paktalin.vocabularynotebook.*
import com.paktalin.vocabularynotebook.ui.fragments.VocabularyFragment
import com.paktalin.vocabularynotebook.utils.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
......@@ -25,6 +27,8 @@ class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
FirestoreManager.vocabularyId = getSavedVocabularyId(this@MainActivity)
swipeRefresh.setOnRefreshListener { refreshVocabulary() }
hideKeyboard()
setUpNavigationView()
extractVocabularyData()
......@@ -47,6 +51,11 @@ class MainActivity : AppCompatActivity() {
startActivity(this@MainActivity, LogInActivity::class.java)
}
private fun refreshVocabulary() {
(recyclerView.adapter as VocabularyAdapter).updateAll()
swipeRefresh.isRefreshing = false
}
private fun setUpNavigationView() {
navigationView.setNavigationItemSelectedListener { menuItem ->
menuItem.isChecked = true
......@@ -61,9 +70,9 @@ class MainActivity : AppCompatActivity() {
private fun extractVocabularyData() {
addProgressBar()
FirestoreManager().extractVocabularyId(
{ id-> addVocabularyFragment(id) },
{ addVocabularyFragment(FirestoreManager.vocabularyId!!) },
{ showToastNoWords() },
{ removeProgressBar() })
{ removeProgressBar() }, this)
}
private fun addVocabularyFragment(vocabularyId: String) {
......
......@@ -28,7 +28,7 @@ class AddWordFragment : WordFragment() {
FirestoreManager().saveNewWord(
{ documentId -> onSuccessfulSave(wordPojo, vocabularyId, documentId) },
{ shortToast(mainActivity, getString(R.string.toast_new_word_fail)) },
wordPojo, vocabularyId)
wordPojo)
}
override fun updateRecycleView(wordItem: WordItem) {
......
......@@ -74,7 +74,7 @@ class EditWordFragment : WordFragment() {
FirestoreManager().updateWord(
{ onSuccessfulSave(wordPojo) },
{ onFailure() },
wordItem, wordPojo, vocabularyId)
wordItem, wordPojo)
}
private fun onSuccessfulSave(wordPojo: WordItem.Pojo) {
......
......@@ -9,7 +9,7 @@ import android.view.ViewGroup
import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentSnapshot
import com.paktalin.vocabularynotebook.*
import com.paktalin.vocabularynotebook.firestoreitems.Vocabulary
import com.paktalin.vocabularynotebook.Vocabulary
import com.paktalin.vocabularynotebook.firestoreitems.WordItem
import com.paktalin.vocabularynotebook.ui.activities.MainActivity
import com.paktalin.vocabularynotebook.ui.views.LockableLayoutManager
......@@ -43,8 +43,8 @@ class VocabularyFragment : Fragment() {
}
private fun extractWordsData(vocabularyId: String) {
FirestoreManager().retrieveWordsData({ documents ->
onSuccessfulWordDataExtraction(documents, vocabularyId)}, vocabularyId)
FirestoreManager().retrieveWordsData { documents ->
onSuccessfulWordDataExtraction(documents, vocabularyId)}
}
private fun onSuccessfulWordDataExtraction(documents: MutableList<DocumentSnapshot>, vocabularyId: String) {
......@@ -57,16 +57,8 @@ class VocabularyFragment : Fragment() {
}
private fun setVocabularyAdapter(documents: MutableList<DocumentSnapshot>, vocabularyId: String) {
val wordItems: MutableList<WordItem> = mutableListOf()
for (ref in documents) {
val word = ref["word"].toString()
val translation = ref["translation"].toString()
val time = ref["time"] as Timestamp
wordItems.add(WordItem(word, translation, time.toDate(), ref.id, vocabularyId))
}
val vocabulary = Vocabulary(wordItems)
val vocabulary = Vocabulary()
vocabulary.addWordsAsDocuments(documents)
val adapter = VocabularyAdapter(vocabulary, mainActivity)
recyclerView.adapter = adapter
}
......
......@@ -62,9 +62,8 @@ abstract class WordFragment : Fragment() {
val word = word.text.toString()
val translation = translation.text.toString()
val vocabularyId = FirestoreManager.vocabularyId
mainActivity.addProgressBar()
saveToFirestore(word, translation, vocabularyId)
saveToFirestore(word, translation, FirestoreManager.vocabularyId!!)
return
}
......
package com.paktalin.vocabularynotebook.utils
import android.content.Context
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
......@@ -9,10 +10,9 @@ import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import com.paktalin.vocabularynotebook.appsetup.ConfiguredFirestore
import com.paktalin.vocabularynotebook.firestoreitems.UserPojo
import com.paktalin.vocabularynotebook.firestoreitems.Vocabulary
import com.paktalin.vocabularynotebook.firestoreitems.VocabularyPojo
import com.paktalin.vocabularynotebook.firestoreitems.WordItem
import com.paktalin.vocabularynotebook.ui.activities.LogInActivity
import com.paktalin.vocabularynotebook.ui.fragments.VocabularyFragment
import java.util.*
class FirestoreManager {
......@@ -20,15 +20,15 @@ class FirestoreManager {
private val db: FirebaseFirestore = ConfiguredFirestore.instance
private val vocabularyCollection = db.collection(VOCABULARIES)
fun extractVocabularyId(onSuccess: (vocabularyId: String) -> Unit,
showToastNoWords: () -> Unit, removeProgressBar: () -> Unit) {
fun extractVocabularyId(onSuccess: () -> Unit,
showToastNoWords: () -> Unit, removeProgressBar: () -> Unit, mainActivity: Context) {
val userId = FirebaseAuth.getInstance()!!.currentUser!!.uid
userDocument(userId).get()
.addOnSuccessListener { snapshot ->
removeProgressBar()
if (snapshot.get(VOCABULARIES) != null) {
setVocabularyID(snapshot)
onSuccess(vocabularyId)
setVocabularyID(snapshot, mainActivity)
onSuccess()
} else {
Log.w(TAG, "There's no collection \"vocabularies\"")
showToastNoWords()
......@@ -38,7 +38,7 @@ class FirestoreManager {
fun addNewUser(firebaseUser: FirebaseUser, logInActivity: LogInActivity) {
//todo add condition to writing to the db in Firebase Console (request.auth.uid)
vocabularyCollection.add(Vocabulary.Pojo(null))
vocabularyCollection.add(VocabularyPojo(null))
.addOnSuccessListener { firstVocabularyRef ->
Log.d(TAG, "VocabularyPojo successfully created: " + firstVocabularyRef.path)
setNewUserWithVocabularyData(firebaseUser, firstVocabularyRef, logInActivity)
......@@ -50,8 +50,8 @@ class FirestoreManager {
}
fun saveNewWord(onSuccess: (documentId: String) -> Unit, onFailure: () -> Unit,
wordPojo: WordItem.Pojo, vocabularyId: String) {
vocabularyDocument(vocabularyId)
wordPojo: WordItem.Pojo) {
vocabularyDocument()
.collection(WORDS).add(wordPojo)
.addOnSuccessListener {
Log.i(TAG, "Successfully added a new word")
......@@ -62,9 +62,8 @@ class FirestoreManager {
onFailure() }
}
fun updateWord(onSuccess: () -> Unit, onFailure: () -> Unit,
wordItem: WordItem, wordPojo: WordItem.Pojo, vocabularyId: String) {
vocabularyDocument(vocabularyId)
fun updateWord(onSuccess: () -> Unit, onFailure: () -> Unit, wordItem: WordItem, wordPojo: WordItem.Pojo) {
vocabularyDocument()
.collection(WORDS).document(wordItem.id).set(wordPojo)
.addOnSuccessListener {
Log.i(TAG, "Successfully updated the word")
......@@ -77,14 +76,14 @@ class FirestoreManager {
}
fun deleteWord(id: String) {
vocabularyDocument(vocabularyId)
vocabularyDocument()
.collection(WORDS).document(id).delete()
.addOnSuccessListener { Log.i(TAG, "Successfully deleted word with id $id") }
.addOnFailureListener { e -> Log.w(TAG, "deleteWordWithId $id:failure", e.fillInStackTrace()) }
}
fun retrieveWordsData(onSuccess: (documents: MutableList<DocumentSnapshot>) -> Unit, vocabularyId: String) {
vocabularyDocument(vocabularyId).collection(WORDS)
fun retrieveWordsData(onSuccess: (documents: MutableList<DocumentSnapshot>) -> Unit) {
vocabularyDocument().collection(WORDS)
.orderBy("time", Query.Direction.DESCENDING)
.get()
.addOnSuccessListener { onSuccess(it.documents)}
......@@ -105,9 +104,10 @@ class FirestoreManager {
}
}
private fun setVocabularyID(snapshot: DocumentSnapshot) {
private fun setVocabularyID(snapshot: DocumentSnapshot, context: Context) {
val vocabularies: List<DocumentReference> = snapshot.get(VOCABULARIES) as List<DocumentReference>
val vocabulary = vocabularyDocument(vocabularies[0].id)
val vocabulary = vocabularyCollection.document(vocabularies[0].id)
saveVocabularyId(context, vocabulary.id)
vocabularyId = vocabulary.id
}
......@@ -115,8 +115,8 @@ class FirestoreManager {
return db.collection(USERS).document(userId)
}
private fun vocabularyDocument(vocabularyId: String): DocumentReference {
return vocabularyCollection.document(vocabularyId)
private fun vocabularyDocument(): DocumentReference {
return vocabularyCollection.document(vocabularyId!!)
}
companion object {
......@@ -125,6 +125,6 @@ class FirestoreManager {
private const val VOCABULARIES = "vocabularies"
private const val TAG = "VN/FirestoreManager"
lateinit var vocabularyId: String
var vocabularyId: String? = null
}
}
\ No newline at end of file
package com.paktalin.vocabularynotebook.utils
import android.content.Context
import android.preference.PreferenceManager
private const val vocabularyIdKey = "vocabularyId"
fun saveVocabularyId(context: Context, vocabularyId: String) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
sharedPreferences.edit().putString(vocabularyIdKey, vocabularyId).apply()
}
fun getSavedVocabularyId(context: Context): String? {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
return sharedPreferences.getString(vocabularyIdKey, null)
}
\ No newline at end of file
......@@ -14,12 +14,12 @@
android:layout_marginRight="@dimen/small_margin"
android:layout_marginStart="@dimen/small_margin"
android:layout_marginTop="@dimen/small_margin"
android:paddingStart="@dimen/small_padding"
android:paddingLeft="@dimen/small_padding"
android:background="@drawable/sheet_top"
android:paddingEnd="@dimen/small_padding"
android:paddingLeft="@dimen/small_padding"
android:paddingRight="@dimen/small_padding"
android:paddingStart="@dimen/small_padding"
android:paddingTop="@dimen/small_padding"
android:background="@drawable/sheet_top"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
......@@ -28,61 +28,66 @@
android:id="@+id/fragmentAddWord"
android:name="com.paktalin.vocabularynotebook.ui.fragments.AddWordFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
android:layout_height="wrap_content" />
</FrameLayout>
<com.paktalin.vocabularynotebook.ui.views.LockableScrollView
android:id="@+id/scrollView"
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipeRefresh"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginEnd="@dimen/small_margin"
android:layout_marginLeft="@dimen/small_margin"
android:layout_marginRight="@dimen/small_margin"
android:layout_marginStart="@dimen/small_margin"
android:scrollbars="vertical"
app:layout_constraintBottom_toTopOf="@+id/btnSubmitLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/container_main">
<LinearLayout
android:id="@+id/container_vocabulary"
<com.paktalin.vocabularynotebook.ui.views.LockableScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/sheet_bottom"
android:orientation="vertical"
android:paddingStart="@dimen/small_padding"
android:paddingLeft="@dimen/small_padding"
android:paddingEnd="@dimen/small_padding"
android:paddingRight="@dimen/small_padding"
android:paddingBottom="@dimen/small_padding">
</LinearLayout>
android:layout_height="0dp"
android:scrollbars="vertical">
</com.paktalin.vocabularynotebook.ui.views.LockableScrollView>
<LinearLayout
android:id="@+id/container_vocabulary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/sheet_bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/small_padding"
android:paddingEnd="@dimen/small_padding"
android:paddingLeft="@dimen/small_padding"
android:paddingRight="@dimen/small_padding"
android:paddingStart="@dimen/small_padding" />
</com.paktalin.vocabularynotebook.ui.views.LockableScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
<LinearLayout
android:id="@+id/btnSubmitLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:visibility="gone"
android:orientation="horizontal"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent">
<ImageButton
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_close_icon"
android:background="@android:color/transparent"
android:layout_gravity="center_vertical"
android:layout_margin="@dimen/small_margin"
android:background="@android:color/transparent"
app:srcCompat="@drawable/ic_close_icon"
tools:ignore="ContentDescription" />
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"/>
android:layout_weight="1" />
<ImageButton
android:id="@+id/btnSubmit"
......
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