As the Android documentation explains https://developer.android.com/training/data-storage/shared-preferences.html?hl=en the Share Preferences is a way to save Key-Value data. Given that that behind scenes that dictionary can be save in almost a random order you can't retrieve something in order. However I can recommend a couple of solutions:
- The easy not good performance one: Add as part of the value the index, therefore you can create an array with the size of the Hashset and then iterate the Hashset and add every element in the array that you created. O(N) temporal complexity plus the one involved in the reading process of the file.
Saved the data in a local SQLite database: This solution is more flexible in future terms (you can add new contacts). https://developer.android.com/training/data-storage/sqlite.html Usually you create your own SQLite database that you put in assets and then you just import it. You can create queries to bring them in the order that you want (maybe create a column for that).
InputStream myInput = context.getAssets( ).open( "test.db" );
// Path to the just created empty db
String outFileName = "/data/YOUR_APP/test.db";
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream( outFileName );
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while( ( length = myInput.read( buffer ) ) > 0 )
{
myOutput.write( buffer, 0, length );
}
// Close the streams
myOutput.flush( );
myOutput.close( );
myInput.close( );
Simple not scalable option: In the values folder
you can always create a strings.xml
file where you can put that data as a string-array
. https://developer.android.com/guide/topics/resources/string-resource.html?hl=en
<string-array name="types">
<item>A</item>
<item>B and users</item>
<item>C</item>
<item>D</item>
<item>E</item>
</string-array>
If you need something more structured I have done stuff like this (saved as JSON).
<string-array name="quality_attributes">
<item>{id:1,name:Performance,sub:[{id:2,name:Scalability},{id:3,name:Response_Time}]}</item>
<item>{id:4,name:Security,sub:[{id:5,name:Availability,sub:[{id:6,name:Reliability},{id:7,name:Recovery}]},{id:8,name:Privacy}]}</item>
<item>{id:9,name:Interoperability}</item>
<item>{id:10,name:Maintainability}</item>
<item>{id:12,name:Testability}</item>
<item>{id:13,name:Usability,sub:[{id:14,name:Findability},{id:15,name:Correctness}]}</item>
</string-array>
And in my code:
String[] elementsArray = getResources().getStringArray(
R.array.quality_attributes);
for (int i = 0; i < attributesArray.length; i++) {
Gson gson = new Gson();
MyJsonObject obj = gson.fromJson(elementsArray[i],
MyJsonObject.class);
// Do something
}
In general terms if you want something that needs to be change, the second options is the best one. If you are looking for something simple, the third option is good enough.