1

So i have made a class DrawView which extends View and i want to draw some graph in that class with the points i stored as int array i made this array like a sort of public variable with the help of How to declare global variables So when i want to get connected with MyApp in Activity and change my array, i simply use

MyApp appState = ((MyApp)getApplicationContext());

but the problem is that this won't work when i call it in my DrawView.java class. Any ides how to solve this?

Community
  • 1
  • 1
Vladimir
  • 1,243
  • 5
  • 19
  • 23

1 Answers1

1

I really don't know why that answer is so up voted as it's not a good solution. The Application object is to run the Application, not to store data, you can solve this MUCH easier with a simple Singleton object, try this:

    public Class MyData{

        private int[] data;
        private static MyData me;

        public int[] getData(){
           return data;
        }

        private MyData(){} // private constructor

        public MyData get() {}
            if(me==null) me = new MyData();
            return me;
        }
    }

than from any object you can call:

    int[] data = MyData.get().getData()

and feel free to expand to more than just a int[] ... put any other object that you want to be globally accessible. But remember, DO NOT KEEP REFERENCES TO THE CONTEXT!

Budius
  • 39,391
  • 16
  • 102
  • 144
  • thanks, i'll have this in mind. does this save my data even if i shut the phone? and why is context such a bad thing? xD – Vladimir Dec 11 '12 at 16:36
  • no. that's a RAM only memory, just like on the other post, it will be gone whenever the Android OS shuts down the VM. For permanent storage please refer to the oficial guide http://developer.android.com/guide/topics/data/data-storage.html – Budius Dec 11 '12 at 16:42
  • the Context have a reference to your whole activity (it's a very big object) and the singleton is an object that lives for a long time. And holding long lived references to big objects chances are 100% that you'll end up having a memory leak. – Budius Dec 11 '12 at 16:44