Dictionary sort? - android

hey,
i have a dictionnary like
"key2","value2"
"key3","value3"
"key1","value1"
is it possible to sort it on value ?
If not, any other object can do same thing? (sort value on key/value pair)

Well, clearly you're talking about a Map.
It really depends on what Map you're using, You don't need to sort a TreeMap, coz it is already sorted.
For any other, You can get the keys using map.keySet() and use Collections.sort() to sort them. (Note, the map will remain the same, you'll get a Set containing all the key values)
Hope it helped.

Related

String Array in SharedPreferences

I need to work with a persistent String Array (n Rows, 1 column).
* On first running the app, the String Array needs to be created empty.
* On subsequent app executions the Array will be populated from a File and the contents need to be available throughout the rest of the app.
* As the app is executed, the Array needs to be able to 'grow' in row count
* As the app is executed, the Array rows need to be able to grow in length
* The user will have the option to Clear the Array of previous entries.
* At the end, the String Array contents will be written back to a File.
I find a lot of references to Putting and Getting from an existing SharedPreferences String[] but, in the newness of my Android development, I am struggling with how to proceed.
EDIT Follows...
The data itself suggests using an Array
Example:
MAIN ST. F55 63 KY08:57 12142015--------KY11:24 12142015345TMH KY13:57 12142015
MAIN ST. F56 WYE123 IN08:57 12142015--------KY11:24 12142015--------KY13:57 12142015
1ST ST. F57 --------KY08:57 12142015--------KY11:24 12142015789FPF KY13:57 12142015
1ST ST. F58 456FPF KY08:57 12142015998FPF KY11:24 12142015--------KY13:57 12142015
1ST ST. F59 789TTM KY08:57 12142015--------KY11:24 121420151234DG KY13:57 12142015
I first need to have this data in a File
Then in one GUI I check for the existence of the file.
If one exists, fine
If none exists, I create one.
Then, in subsequent GUI's, I must check for the existence of parameters
If they do not already exist, add them to the existing data lines.
If they already exist, notify the user
And so on and on.
Then when all of the current 'pass' data has been collected via multiple, separate GUI's, I have to write out the whole data-set into the file.
My reason for thinking that I need a SharedPreference approach is the need to find and check data from GUI to GUI as the user progresses through the app.
If that 'belief' is wrong, I am open to better approach suggestions.
EDIT 2 follows....
On further study of web references, I am beginning to think that perhaps the best approach for this data and how the data needs to change might be to use a SQLite approach. Any ideas about this?
Any assistance/suggestions you might have would be greatly appreciated.
i would discourage you from using sharedpreferences for anything else than preferences. means things that change rarely - really rarely and are really lightweight. do not put much data in there. less is better. the data structures underlying sharedpreferences are not a database.
another note. it is not a string list, but it would be a string set. sets are not necessarily ordered, nor do they necessarily keep their order. means - it is not rows. its a collection of strings that can come back in any fun order (usually there is some, but that depends on the implementation which i do not know)
now you could go and make your own list, your own data structure, save it into a string and read it out, use json to do exactly that or something similar, or better - use a database, which would exactly do that.
http://developer.android.com/training/basics/data-storage/databases.html
explains it, but as you'll see its something that might take some time.
now dont get me wrong, but i have to warn you about the following approach. it is valid, but has many problems and is far from thread safe. it will not be a problem as long as you only open it from the ui thread and do not keep anything in memory to cache - if you do it will create lots of problems.
your problem of adding a line and clearing can be solved by using a file. just a simple file
look here
http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage
the change is to append when writing:
openFileOutput("filename", Context.MODE_APPEND);
see the context mode? now you can basically just write one line and append every time.
if you wanna clear the file, just deleteFile("filename")
this is as said not threadsafe, but can be a viable option if used carefully.
Please follow this step to achieve what you want with sharedPreference
create the class Parent for SharePreference
Create your empty Array
Convert Your empty array to String and put it on SharedPreference
to call your empty array from sharedPreference
Call your sharedPreference using your key
Convert the String to array
You get your array from the sharePreference
Hope it helps, and maybe this link will help you :
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
You can use my open-source library called prefser, which solves this problem and uses SharedPreferences and Gson under the hood. It's basically wrapper for default Android mechanism.
You can use it in the following way:
Prefser prefser = new Prefser(context); // create Prefser object
prefser.put("key", Arrays.asList("one", "two", "three")); // save array of Strings
String[] value = prefser.get("key", String[].class, new String[]{}); // read array of Strings
For more information check repository of the project, tests and README.md file.
Link: https://github.com/pwittchen/prefser
Please note, SharedPreferences have some limitations and shouldn't be used for storing large amount of data. If you expect a lot of data, consider using SQLite database or another type of database (e.g. with NoSQL or similar approach if you strive for simplicity).
OK, based on the data, how it needs to be manipulated and the pros and cons of using a SharedPreferences approach, I have decided to go with a SQLite approach.
With that approach I should be able to readily check:
* if the necessary table exists (if not create it)
* if the necessary Field1 + Field2 exists (if not create a new record)
* and I will be able to modify the record's Field3 contents as needed
Then when the user's actions are complete I can convert the SQLite table 'records' into strings and write them out as a File and then either DROP or PURGE the associated SQLite table (until needed next time).
I sincerely appreciate all of your suggestions.
Thank you.

Dynamic properties specified by user

i was wondering if there is a chance to create comparable properties for objects defined by the user itself.
Following case: In my android app, the user creates a object "car", this object has predefined properties like color, size, doors, engine and so on ... but now, the user wants to add an individual property like "length" ... for that the user gets a plus button under the view to add this property ... now he can type in the wanted property, but what he dont want is to define the type of the input!
The users thinks "hey, its pretty obvious that length is expressed with a number so why i have to choose the type for this?"
I dont want to limit the user if i give them only predefined propertys.
I thought about saving every new parameter as a string, but then the values arent comparable anymore ... "900" is bigger than "1000" in a string comparison and so on. And i want to filter data and do queries later.
I dont disagree at all with the idea to let the user choose which type the field is, but i dont want to ask them too much in an android application.
If this all is not possible, how can i smartly get the information for the type from the user?
How can i handle this problem? Can someone give me a hint or keyword to search for?
Natural sorting might be the thing you are looking for. It will solve the problem with numbers.

make list android

I want to create some a dynamic list some thing like hash table
so I can put a key with value or I read list
I want to save it and able to read it when pogrom started .
is it possible ?
Seems like you are looking for HashMap
You will need to serialize / deserialize the map to save/load it.
you are asking for something like hash table where you can save key value pairs you can use also shared preferences for that.
http://as400samplecode.blogspot.in/2011/11/android-shared-preferences-example_12.html
Question: is it possible? Answer: yes, it is.

Best way to save data

The thing is I need to store something like:
100 strings
20-30 ints
As you can see, it's a pretty large number, and you might say "Use sql"! I would use sql but for me it looks kinda alien. It's a lot of code, and after that I can't find a tutorial that shows you: look, you make a database with tables like this, and then you read it like this, you can also search in it like this...
Can you please give me the best method to save that data? And if you say sql, please give me a tutorial or something that shows me how to do what I said above.
I would say you should look into SQLite and try to learn that. But if you really want to stay away from SQL you could use putStringSet to store your strings in SharedPreferences. Now there isn't a thing for putIntSet but you could convert your ints to strings using String.valueOf(myInt) and save it using the same putStringSet. I would like to be clear though, I think that a database is the way to go on this but this method should work for you.
If you use SQl, look at ORMLite, which will let you store objects in the db (http://ormlite.com/). For 100 strings, if they're basically name/value pairs, just use SharedPreferences http://developer.android.com/reference/android/content/SharedPreferences.html. Could also use static string resources, as mentioned.

Which Preference Class for an Integer?

To store an integer in an Android preference, I would intuitively go for EditTextPreference and do the usual String-int-String conversions.
But then I came across a piece of code that stores an integer in a <ListPreference> instead:
<ListPreference
android:key="#string/total_score"
android:defaultValue="0" />
and retrieves it using preferences.getInt(getString(R.string.total_score), 0);
Does this really work? If so, how?
Is it considered acceptable practice?
UPDATE: Thanks to the answers below, I have been able to find the implementation source code for getInt(). I am posting it here for easy reference:
jint android::content::SharedPreferences::getInt(local_ref< java::lang::String > const &a0, jint a1)
{
return call_method<
android::content::SharedPreferences::J2CPP_CLASS_NAME,
android::content::SharedPreferences::J2CPP_METHOD_NAME(2),
android::content::SharedPreferences::J2CPP_METHOD_SIGNATURE(2),
jint
>(get_jobject(), a0, a1);
}
In theory, yes you can store an integer with a ListPreference. After all it's a UI-preference that maps a user displayed label/key (android:entries) to an internal value (android:entryValues) and displays all those mapping options in a listview. That internal value might as well be an integer. You could use a <integer-array>-resource for the entryValues.
In practice, I've never seen that work - it's bugged.
Of course, you can set a int value to the preference key of the ListPreference in your code, since it's a normal preference internally. But that would defeat the whole purpose of predefined resource arrays and ability to select from a list. As a workaround, if a int-array would be handy, I recommend using a <string-array> for the values and convert them an integer in code, as you would with your EditTextPreference
Check this question for a non-working example. ;)
To answer your title question which one to choose for an integer: Depends.
You can use either one with the workarounds.
If the user should be able to enter any value (or just a lot of values), the EditTextPreference is the way to go. A ListPreference would just be too long.
If you have a small set of predefined ints, use a ListPreference. Thats way more comfortable to use and might be displayed with useful labels. Example: If the user is supposed to select a timing interval, you could map the seconds in the value and display a different label, e.g. an hour [value 3600; label "Hour"].
Edit: Also got an idea where your code snippet may be related to. Since this ListPreference does neither specify android:entries nor android:entryValues, it might just be part of a default preference file. You can use PreferenceManager.setDefaultValues() with an XML file to reset/initalize all your preference keys. In this case it's completely random which preference you choose, because all fields that count are android:key and android:defaultValue. You might use any other type in this case, does not matter.
I think what's going on is that the ListPreference is storing the entry values as an array of chars, or in other words an array of bytes (I'm inferring this from the setEntryValues(CharSequence[] entryValues) method). This could be why storing a number works, because the value is stored into the byte array, so using the preferences.getInt(...) method will still work. This could be dangerous, however, as discrepancies with signing could occur, so I wouldn't recommend it, and would parse the int from a string preference instead.

Categories

Resources