Saving user list data in android compose - android

So im trying to understand how data is saved on android. I am currently working on a simple notes app. How it currently works, is the user creates a new note, types whatever they want, and once they hit the back button that entry is saved in to a list. I am using compose viewmodel so the entries are saved up until the point the app is destroyed. what is the best way to save the list entries so they are pemenantly saved on the phone. This is also just a general question on how apps generally save user input data that is not saved in the cloud.
here is some example of the code.
data class NotesBlueprint(
val header: String,
val note: String,
val key: Int
)
data class NotesVars(
val header:String = "", <<<< instance of header and the note
val note: String = "" <<<<
var list: List<NotesBlueprint> = mutableListOf() <<< list that the Notes are saved in to
)

You can store the data on android via Shared Preference, Database, and Files. This storage overview guide gives the idea regarding different types of the storage system and how they are saved on android.
In your case, if you want to save notes which user has written, it would be better to go with the database.
Android provides the Room library for storing data in the local database. You can check out the guide here.

Related

Can not get a key value from Firebase storage in kotlin

I cannot get a key value from firebase storage while datas exist in storage.
key = intent.getStringExtra("key").toString()
and they return null
binding.writebtn.setOnClickListener {
val title = binding.titleArea.text.toString()
val contents = binding.contentArea.text.toString()
val uid = FBAuth.getUid()
val time = FBAuth.getTime()
val key = FBRef.boardRef.push().key.toString()
FBRef.boardRef
.child(key)
.setValue(BoardModel(uid, title, contents, time))
and this is my saving function.
and as u can see, all datas are saved properly. But still I cannot get a key value.
If you want to get data from any database you need to use any clinter (Retrofit) if you have this code please share otherwise check this thread. The GetStringExtra() you are currently using is for getting shared data between android core components and it has nothing to do with firebase database.

How to add data to the firebase firestore by generating different document id after hitting submit button again and again? Android Kotlin

I am trying to push the form data to the firebase-firestore. And I also did it successfully. But, the problem is that whenever I am trying to submit the form data again and again it just updates the last data with the current data.
Actually, my requirement is that whenever the user hit the submit button. It creates a document with a random id and stores the all data into that specific id that is generated.
You are specifying the document ID in .document() so it'll overwrite the same document. If you want a document with a random ID on every click, try using add() instead as shown below:
val collectionRef = FirebaseFirestore.getInstance().collection("Maintainance")
collectionRef.add(user).addOnCompleteListener(...)
Alternatively, you can leave .document() empty to get a DocumentReference with a random ID:
val userDocument = FirebaseFirestore.getInstance().collection("Maintanance").document() // <-- don't pass an ID
In addition to #Dharmaraj answer:
CASE_1: In a case where you need to track each user's all submitted forms, probably from your explanation you may need to organize each user's form.
Therefore if you need to organize each user's form then create another sub-collection [example: document(userId).collection("USER_FORMS")] within userID document like this:
val documentRef = FirebaseFirestore.getInstance().collection("Maintainance").document(UserUtils.user?.id.toString()).collection("USER_FROMS").document();
CASE_2 : In a case where you need to make your own custom document ID:
1- make a random number or string or any other data type.
2- The random number/string variable must be local to the code block/method that will execute the form submision function.
3- use the number/string generated as the form document Id like this:
//This must be local so as user clicks submision button so as it generates new random number;
val randomFormId = "generateThenumberOrStringAndInitializeTheVariable";
Then use the random number as the form document Id like this:
val documentRef = FirebaseFirestore.getInstance().collection("Maintainance").document(UserUtils.user?.id.toString()).collection("USER_FROMS").document(randomFormId);

Is there a better way of retriving Document Refernce?

I am new to Firestore and I am developing an android app where I am loading comments in Recycler View.
Below is sample data class for comment.
data class Comment(
val id: String,
val text: String,
val user: DocumentReference
)
Currently I am using this below code in onBindViewHolder in adapter
comment.userId.get()
.addOnCompleteListener {
if (it.isSuccessful) {
val u = it.result.toObject(User::class.java)
user = u.name
binding.userTv.text = user
}
}
binding.commentTv.text = comment.text
I have to explicitally run Task<TResult> every time to fetch the user in adapter.
I am looking for a better way to retrieve user from comment to display username is a single query.
Typically when dealing with usernames that may update regularly, traditionally you would store the raw user name string in each document which requires heavy read/writes to keep it updated. Instead, it has been found better to store them in a master document/collection that assigns all user UID's with the display name as the value, allowing you to look up any user UID and know it from one source of truth.
This has been made easier with the new Bundle Feature which allows all apps to preload documents in your app to prevent the need to fetch them every time. The only catch is you will need to retrieve the data when a new user isn't in their cached data yet or have a dedicated source for all new users to reduce overhead in those situations.
Source: Data Bundles

Cloud Firestore: add OR update an array

I am creating an app where users can upload photos and tag them, and then tags that they have uses are added to the list of that user's interests.
I am making a transition from Realtime database to cloud firestore and having a bit of an issue.
I want to store all these tags in an array inside a document for each user. Whenever a user uploads a photo, these tags should be added to this array.
I am using the update method as I don't want the list to be overwritten, but the data doesn't seem to be created at all. Could it be because for a new user the list doesn't actually exist?
I need the function to create the document and array if it is the first time the user adds any interests, or just update the list and add items if the array already exists.
Also, the tags are added to a complete list of all the tags across the app. For this one I've tried to use the set method but then the list just gets completely overwritten, even when I added SetOptions.merge()
val db = FirebaseFirestore.getInstance()
val userInterestsDoc = db.collection("interests").document(currentUser.uid)
val allTagsListDoc = db.collection("all_tags").document("all_tags")
for (tag in imageTagsList) {
userInterestsDoc.update("interests_list", FieldValue.arrayUnion(tag))
.addOnSuccessListener {
allTagsListDoc.set(
mapOf(
"all_tags_list" to arrayListOf(tag)
), SetOptions.merge()
)
}

Android 3 linked values

What would be the best way to store multiple 3 linked values (String, String, Boolean)? Like in a HashMap for example.
I need to:
save them in SharedPreferences
load them of sp (of course)
change at least the last value dynamically
get all items where the last value is true (for example)
You have three options:
Store it on preferences
Store it in a database
Save a file on disk
If you want to proceed with preferences I will suggest you to convert the 3 value format to a Json format and store it in preferences as json.
{"value1":"value", "value2":"value", "value3":"value"}
or
{"data":"some data",
"link":{
"data":"other linked data",
"link":{...}
}
}
This kind of data is also stored perfectly in a noSQL database. But if you do not want to add a database at all to your project, maybe you can have a look to some noSQL libraries like SimpleNoSQL (it indeed uses a database behind the scenes, but abstracts you very well from it) or Realm (it stores on disk).

Categories

Resources