1

I am posting some code to understand which array can be used globally in any activity and the array may be needed in any activity.

     Intent intent          =   getIntent();
     JSONArray beaconsArray     =   null;
     String jsonArray       =   intent.getStringExtra("activeBeaconsArray");
     try 
        {
            beaconsArray = new JSONArray(jsonArray);
            System.out.println(beaconsArray.toString(2));
        } 
     catch (JSONException e) { e.printStackTrace();}

Should i store beaconsArray in any static array variable in a separate class so that I can use it any activity wherever needed OR should I make parent class that will be super class of all those classes which need this array (beaconsArray ) ?
I do not want to fetch it again and again from database!

Muhammad Irfan
  • 1,447
  • 4
  • 26
  • 56
  • i agree. this is exactly the kind of thing shared preference files are for. parse the json and save the key value pairs – toadzky Oct 10 '12 at 13:34

2 Answers2

2

Create a class which extends Application class and add your data to it. Any data you add to it will be persistent till the app ends.

A good example can be found here,

Using the Android Application class to persist data

http://www.helloandroid.com/tutorials/maintaining-global-application-state

or you can go for Sharedperefernce. But you have to understand that data added to them are persistent unless you overwrite it.

Community
  • 1
  • 1
Andro Selva
  • 53,910
  • 52
  • 193
  • 240
  • 2
    This is the better answer. The application object lasts throughout the life cycle of the app until it is killed off by the operating system (or a task killer), and it can be easily accessed from anywhere. SharedPrefs require the user to keep it updated and modify it accordingly. – Joss Stuart Oct 10 '12 at 13:38
2

SharedPreference is preferred for these kind of task below give some utility method for saving JSONArray in SharedPreference

public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
    SharedPreferences settings = c.getSharedPreferences(prefName, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
    editor.commit();
}

public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
    SharedPreferences settings = c.getSharedPreferences(prefName, 0);
    return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, ""));
}
Animesh Sinha
  • 1,045
  • 9
  • 16