'How to create an ArrayList that is accessible by different classes in android? [duplicate]
I got a CameraView class (with an onPreviewFrame) which on each incoming frame calculates a value of 1 or 0 depends on the frame brightness, I want that on each incoming frame the calculated value will be add to an ArrayList. The problem begins when I need to read the data that is in the ArrayList from my MainActivity class.
How do I create a list that different class can get to?
I know it's relatively simple but i'm new to java/android and trying to wrap my head around how it all works.
Solution 1:[1]
Here is an example of what I recently used when I needed to send a HashMap from one activity to another:
Intent i = new Intent(getApplicationContext(), BillPage.class);
i.putExtra("workPriceMap", (HashMap<String, Float>)workPriceMap);
startActivity(i);
And then in my other class I used this:
private Map<String, Float> workPriceMap;
workPriceMap=(HashMap<String,Float>intent.getSerializableExtra("workPriceMap");
Solution 2:[2]
You could use a singleton method, this way you can have the same reference everywhere.
public class YourClass {
private ArrayList<String> yourList;
private YourClass instance;
private YourClass(){
yourList = new ArrayList<>();
}
public static YourClass getInstance(){
if(instance == null){
instance = new YourClass();
}
return instance;
}
public ArrayList<String> getYourList(){
return this.yourList;
}
}
public class OtherClass{
public static void main(String [] args){
ArrayList<String> yourList = YourClass.getInstance().getYourList();
}
}
Solution 3:[3]
You can create a singleton class, like below:
public class Singleton {
private static Singleton instance;
private List<String> frameList;
private Singleton() {
this.frameList = new ArrayList<String>();
}
public static Singleton getInstance() {
if(instance == null)
instance = new Singleton();
return instance;
}
public List<String> getList() {
return this.frameList;
}
public void setList(List<String> frameList) {
this.frameList = frameList;
}
}
You can then access it from any class by:
Singleton.getInstance().getList().add("x");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Trey50Daniel |
Solution 2 | Arturo Mejia |
Solution 3 | Ryan M |