Android:- How to Make dynamic HashMap Accessible in whole application? [duplicate]

与世无争的帅哥 提交于 2019-12-12 01:57:31

问题


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.



来源:https://stackoverflow.com/questions/7200940/android-how-to-make-dynamic-hashmap-accessible-in-whole-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!