how to return sharedpreferences's value? - android

I'm using sharedpreferences to store user's Governorate. It's already saved in an xml file, but always returns default value
How can I return SharedPreferences's value?
enter image description here
enter image description here
Kotlin
governorate_main.setOnClickListener {
val view = layoutInflater.inflate(R.layout.add_photo, null)
val alertBuilder = AlertDialog.Builder(this)
alertBuilder.setView(view)
val alertDialog = alertBuilder.create()
alertDialog.show()
view.save_governorate.setOnClickListener {
mShared = getSharedPreferences("mShared", 0)
val radioId = view.radioGroup.checkedRadioButtonId
radioButton = view?.findViewById(radioId)
radioSelected = radioButton?.text.toString()
val editor:SharedPreferences.Editor = mShared!!.edit()
editor.putString("governorate", radioSelected).toString()
editor.apply()
alertDialog.dismiss()
}
val databack: SharedPreferences = getSharedPreferences("mShared", 0)
governorate.text = databack.getString("governorte", "Please choose your country")
}

Root cause: You are using 2 difference keys to store and retrieve a value from SharedPreferences, governorate is different from governorte.
Solution: You should define the key as a static constant then using it when store and retrieve a value.
companion object {
val PREF_GOVERNORATE: String = "governorate"
}
Store:
editor.putString(PREF_GOVERNORATE, radioSelected).toString()
Retrieve:
databack.getString(PREF_GOVERNORATE, "Please choose your country")

You made a spelling mistake, you're saving as governorate but trying to fetch governorte
Also it probably isn't a good idea to nest click listeners

Related

android SharedPreferences order/sort by field

i am retrieving all SharedPreferences inside my app like this:
getCollection() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getInt("collectionCount") == null) {
clearCollection();
} else {
collectionCount = prefs.getInt("collectionCount")!;
url = prefs.getStringList("collectionUrl")!.reversed.toList();
method = prefs.getStringList("collectionMethod")!.reversed.toList();
headers = prefs.getStringList("collectionHeaders")!.reversed.toList();
body = prefs.getStringList("collectionBody")!.reversed.toList();
name = prefs.getStringList("collectionName")!.reversed.toList();
syntax = prefs.getStringList("collectionSyntax")!.reversed.toList();
}
}
Is there a way to order the output by the name (collectionName) field in alphabetic order?
Instead of using reversed try with sort function.
Here some info about sort function (i think that language is dart): Sort a list of objects in Flutter (Dart) by property value

Is there a better way to retrieve lists of object from Firebase in Kotlin?

I have been playing with Firebase in my Android app and have been having trouble with reading data from the DB. I store a list of objects that contains some properties as well as another list of other objects inside the DB. While the storing works fine, I can't seem to easily get the data back. I'd ideally like to cast directly to an object (or even to the list) but here is what I came up with:
app.db.child(app.UID).get().addOnSuccessListener {
for (trip in it.children) {
val name = trip.child("name").value as String
val description = trip.child("description").value as String
val tripDate = trip.child("tripDate").value as Long
val isActive = trip.child("active").value as Boolean
val dateCreated = trip.child("dateCreated").value as Long
val dateCompleted = trip.child("dateCompleted").value as Long
val id = trip.child("id").value as String
val travel = Travel(name, description, tripDate, isActive, dateCreated, dateCompleted, id)
println(travel.toString())
for (stop in trip.child("stops").children) {
val stopName = stop.child("name").value as String
val stopNotes = stop.child("notes").value as String
val complete = stop.child("complete").value as Boolean
val dateTime = stop.child("dateTime").value as Long
val stopId: Int = (stop.child("id").value as Long).toInt()
travel.stops.add(TripStop(stopName, dateTime, stopNotes, stopId, complete))
}
app.data.add(travel)
}
}
While it does work, I can't help but feel there is a better way to do this. Can someone point me in the right direction? Thanks!
P.S. I'm only trying to get the data once (once the application opens), so the event listeners on data change don't really make sense

I want to use var to determine which photo to load into the image-view- Kotlin

I have a var with kind of food in it (For example: pizza, burger ext.), I want to use that var to load a apecific image based on that var value from my drawable directory into the image view without using when.
I have those files: pizza.png, burger.png
I want to use something like this:
var food = "pizza.png"
food_icon.setImageResource(R.drawable.food)//image is the pizza
food = "burger.png"
food_icon.setImageResource(R.drawable.food)//image is the burger
Is there a way to do this?
If I understand your question correctly you can use following method:
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier("[your_drawable_name]", "drawable", context.getPackageName());
return resources.getDrawable(resourceId);
With this you can specify the name of your rawable and load it.
If you need only the resourceId you can return the resourceId without getting the drawable itself.
You could use an enum which corresponds to the right drawable for example
enum class FoodTypes(private val value: Int) {
PIZZA(R.drawable.pizza),
BURGER(R.drawable.burger);
fun getValue(): Int = value
}
Then you can use it like this
var food = FoodTypes.PIZZA
food_icon.setImageResource(food.getValue())
food = FoodTypes.BURGER
food_icon.setImageResource(food.getValue())
why not doing this ?
var food = R.drawable.pizza
food_icon.setImageResource(food)//image is the pizza
food = R.drawable.burger
food_icon.setImageResource(food)//image is the burger

Local variables won't change inside OnCompleteListener

What I'm trying to do here is to get all the needed information from the database and use it to create a new Account instance. However, for some reason after the addOnCompleteListener part ends the values name, username,...etc won't change. Why is that?
private fun initlAccount(uid:String):Account{
var name = ""
var username = ""
var dob = ""
var email = ""
val friends = ArrayList<Account>()
var tasks = ArrayList<Task>()
db.collection("users").document(uid).get().addOnCompleteListener {
if(it.isSuccessful){
name = it.result.getString("Full name")!!
username = it.result.getString("Username")!!
dob = it.result.getString("Date of Birth")!!
email = it.result.getString("Email")!!
var arrtemp = it.result.get("Friends") as ArrayList<String>
for(str in arrtemp){
friends.add(initlAccount(str))
}
arrtemp = it.result.get("Tasks") as ArrayList<String>
tasks = getTasks(arrtemp)
}
}
val acc = Account(uid,username,name,dob,email,tasks,friends)
println(acc.toString())
return acc
}
val acc = Account(uid,username,name,dob,email,tasks,friends)
println(acc.toString())
return acc
this code gets executed before the code inside on onCompleteListener. You should create the Account inside the completion listener. Ofcourse you can't return from inside the listener, so make the val acc as a member variable instead of local. I don't know your complete code, so can't give much suggestion regarding that.
The values are changing, just not when you are expecting them to
Change the method signature to pass in the completion listener and return nothing
private fun initlAccount(uid:String, listener:OnCompleteListener) {
...
db.collection("users").document(uid).get().addOnCompleteListener(listener)
} // End of method
Move the listener body to the place you call this method, which makes it "callback" into the other thread and therefore "returning the execution results"
Note: I don't know Kotlin, but something like this
initlAccount("uid-value", OnCompleteListener { it ->
if(it.isSuccessful){
val result = it.result
name = result.getString("Full name")!!
username = result.getString("Username")!!
dob = result.getString("Date of Birth")!!
email = result.getString("Email")!!
var arrtemp = result.get("Friends") as ArrayList<String>
for(str in arrtemp){
friends.add(initlAccount(str)) // Note: This is recursive, and will be an issue
}
arrtemp = result.get("Tasks") as ArrayList<String>
tasks = getTasks(arrtemp)
val acc = Account(uid,username,name,dob,email,tasks,friends)
println(acc.toString())
// Your account is returned here, so you can update a UI element, for example
}
}) // end initlAccount method call
// do NOT use acc here, it will be unassigned or null
And I see you are doing a recursive call, so you should either make the database query handle that itself so the client is not in an endless cycle (a "friendship" should be reflexive - userA is a friend of userB, so getting the account of userB would return back to getting the friends of userA, and continue on) or you can try researching RxJava / Kotlin flatMap operators.
Instead of creating a method that returns an Account.
Why not query directly to retrieve the Account? because doing it results in an unsynchronized workflow.
db.collection("users").document(uid).get().addOnCompleteListener {
if(it.isSuccessful){
name = it.result.getString("Full name")!!
username = it.result.getString("Username")!!
dob = it.result.getString("Date of Birth")!!
email = it.result.getString("Email")!!
var arrtemp = it.result.get("Friends") as ArrayList<String>
for(str in arrtemp){
friends.add(initlAccount(str))
}
arrtemp = it.result.get("Tasks") as ArrayList<String>
tasks = getTasks(arrtemp)
val acc = Account(uid,username,name,dob,email,tasks,friends)
println(acc.toString())
// Probably do a save in Database?
}
}

Android comparing strings with == to each objects

I'm coming from C#, so typically I try to relate everything that i'm doing.
I cannot figure out why the below statement doesn't work. Basically String val = "admin". Then an I have an if statement, however the if statement is always false. I'm sure it's something simple.
Thanks!
EditText edt = (EditText) findViewById(R.id.email);
//String val = edt.getText().toString();
String val = "admin";
EditText edt2 = (EditText) findViewById(R.id.password);
String val2 = edt2.getText().toString();
if(val.toString() == "admin") {
String hero = val;
}
You should use
if (val.equals("admin")) {
String hero = val;
}
instead of using an equal sign. Using an equal sign in java is asking if they're the same object, which will be false even if the strings are the same.
Also, be careful with what you're doing inside of the if statement, because the variable "hero" won't be accessible outside of that block.
In Java you can't compare strings using ==
You need to change your if statment like this
if(val.equals("admin")){}
First of all you have never changed the value of String val to anything so there is no need to try convert it to a string in your if statement.
String val = "admin";
if (val == "admin") {
//code here
}else{
//code here
}
Hope this helps
In java, == operator check the address of each value, and equals() method check the value.
So If you want to compare the value of each string, you should use the equals() method.
Please search for the concept of 'call by reference' and 'call by value'.
And you already declare val to String, so it didn't need toString().
if(val.equals("admin")) {
String hero = val;
}
I'm surprised no one mentioned the difference between .matches() and .equals() depending on your needs, what you could also be looking for is .matches()
if(val.toString().matches("admin")) {
String hero = val;
}
Matches checks the match of a String to a regular expression pattern, not the same string.
For example:
"hello".equals(".*e.*"); // false
"hello".matches(".*e.*"); // true
use .equals() instead of ==.
for example:
if (val.equals("admin")) ...

Categories

Resources