Android:- How to Make dynamic HashMap Accessible i

2019-08-24 01:02发布

问题:

This question already has an answer here:

  • How to declare global variables in Android? 17 answers

I have one problem is i am parsing data from google api which returns me JSON data. I stored that data in HashMap<string,String>. which is dynamic. Now i want to make it accessible in my another classes of application. so i am confuse how to make it accessible in other classes without making static. is there any solution? if u have any sample code please send. i tried using static Map<String, String> map = new HashMap<String, String>(); but it dosen't make scence because responce is dynamic. So i need dynamic hashmap which can be accessed in more than one class.

Thanks for help. Mahaveer. mahaveermuttha@gmail.com

回答1:

Android provide Application Context that you could subclass and use it in other activities. The steps are (I also highlight the links so you could read up on important things):

  • Modify your Android Manifest to include the custom Application. Look at the following section in your AndroidManifest.xml


    <application android:icon="@drawable/icon" android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" android:name="com.mypackage.application.MyCustomApplication">
....

The android:name="com.mypackage.application.MyCustomApplication" referring to the class MyCustomApplication which is the subclass of Application that you are going to create

  • Now, it's time for you to make your subclass. In here you want to make sure you include HashMap<string,String> as part of its variable. So your subclass would look like

    public class  MyCustomApplication extends Application {
        HashMap myMap;

        public MyCustomApplication() {
            this.myMap = new HashMap();
        }

        public HashMap getMyMap() {
            return myMap;
        }
    }
  • Once you do that, now you can access your map from any Activity by calling getApplication(). Make sure you cast the Application to MyCustomApplication to use it properly and get access to the method getMyMap()

Let me know if you need further clarification



回答2:

You could try creating a custom Application object and making the HashMap a field on that Application object. All your Services and Activities could then access it there.