android SharedPreferences order/sort by field - android

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

Related

Not able to retrieve proper value from stored shared preference in Flutter

I have use shared preferences for store api token.but it not return full token. always missing some letters from end of token.
this is how a tried.
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("bearer_token", response.data!.accessToken ?? "");
SharedPreferences prefs = await SharedPreferences.getInstance();
token = prefs.get('bearer_token').toString();
To accept null value while receiveing you need to change
token = prefs.get('bearer_token').toString();
to
token = prefs.getString('bearer_token');// now it return nullable string
And it should define like String? token;.
Also you are saving empty string on null case.
You can do
prefs.setString("bearer_token", response.data?.accessToken ?? "");
Now check empty string like
final result = prefs.getString('bearer_token')??"";
if(result.isEmpty){
///....
}

how to return sharedpreferences's value?

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

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?
}
}

How to valid sharedpreference value in android?

I am checking all these at splashscreen activity,
So I am giving this,
SharedPreferences spf = getSharedPreferences("myprfs", Context.MODE_PRIVATE);
SharedPreferences.Editor spe = spf.edit();
String name = spf.getString("name","");
String id = spf.getString("id","");
String class = spf.getString("class","");
String roll = spf.getString("roll","");
spe.commit();
if((spe != null) && (name != null) && (id != null) && (class != null) && (roll != null)){
Intent i = new Intent(Startpage.this,Welcome.class);
startActivity(i);
Startpage.this.finish();
}
else{
Intent i = new Intent(Startpage.this,MainActivity.class);
startActivity(i);
Startpage.this.finish();
}
when I open app startup page directly moves to welcome page,
but I want to move splashscreen page to MainActivity when there is no values saved in shared-preferences
I followed this to get shared-preference values
can any one suggest me how to give condition in this kind
spf.getString("name","");
return as default value a empty string.
Idea:
why not use
spf.contains("name")
that return true or false?
Alternatively you can check if string is empty or null with TextUtils.isEmpty()
method.
String name = spf.getString("name","");
This method creates a shared pref if it doesn't exist already with the default value as the second argument. So in your case, shared pref are saved with empty string as value when user visited the app for first time.
Just change your default value to null since your checks are on null value and it will work -
String name = spf.getString("name",null);
you are putting null check on the string but while reading from the shared preferences you are setting them to empty string if the value is not found in the shared prefs. change your checks to String.isEmpty() in your if condition.
because null and ""are different,
You should use android.text.TextUtils.isEmpty(CharSequence str)instead of str != null
Another way is :
String name = spf.getString("name",null); ,and then like if (Str != null)
For me,i always usee the first way i said to determine whether String is empty.
Hope it helps you :)

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