开发者

Android - Reading common data between Activities using a Spinner

I have an Android application which retrieves from a external server, a name and a corresponding ID (this could be 1 name and ID combo or multiple name ID combinations), these are all stored in a HashMap<String, String> - The ID as the key and the Name as the value.

What I then would like to implement is a dynamic Spinner that populates itself with the 'Names' from this HashMap and when the user selects one of these names a setting somewhere I set to the ID number. This ID number will then be used in later server requests.

My question is what is the best way to implement this custom Spinner from the HashMap so that when the option is selected the ID number is set somewhere. This ID number has to be accessible from several activities - the spinner is present in several different activities... but should have the same effect on each screen.

Design patterns and pseudo code would be hugely appreciated. At the moment the Spinner is on 2 different screens, at the top below the ActionBar, but obviously the code is in both XML layout files.

Cheers.

EDIT

Code to set names and IDs in HashMap:

// Returns a Map of blog name to blog ID associated with the authenticated user
    public Map<String, String> extractBlogInfo(XMLDataExtracter blogData)
    {
        Log.d(TAG, "BlogOperations::extractBlogInfo()");

        ArrayList<String> blogIDs = new ArrayList<String>();
        ArrayList<String> blogN开发者_如何学编程ames = new ArrayList<String>();
        Map<String, String> blogIDNamePairs = new HashMap<String, String>();

        // Get ID and Names and store them in blogIDs and blogNames variables       


        if (blogIDs.size() == blogNames.size())
        {

            for(int i = 0; i < blogIDs.size(); i++)
            {
                blogIDNamePairs.put(blogIDs.get(i), blogNames.get(i));
            }
        }
        else
        {
            // An error occured
            Log.d(TAG,
                    "BlogOperations::extractBlogInfo() > An error occured - ID and Name array sizes do not match");
            return null;
        }

        return blogIDNamePairs;
    }


For this you can use Shared preference.. You get the Id of the selected value from spinner and stored it in shared preference..

So that you can access this value any where inside your Apps..

If you want to display the selected spinner value from Say Activity1 in Activity2 get the value from Shared preference, now it will be Id so get the corresponding Name from the Id in hash Map..

For shared preference take a look at this... and this....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜