Tajinere Tajinere - 9 months ago 39
Android Question

How to save array to memory in Android

i'm new to android and i'ld like to understand how i can save an array to memory. I don't mean internal memory, as i know about shared preferences, external storage and sqlite. I'm looking at something within the range of RAM/Heap.

The actual challenge is that i have a string array of names. I get the names from an sqlite database when app is first started.

e.g

String[] names = new String[] {"dave", "james", "tommy" }


This list can grow to contain over 10000 items.

In another activity, i want to check if some names exist in the list. I don't want to query the database back and forth to achieve this. That is why i'm thinking that saving in memory may just be the best bet as it can improve performance.

So i'ld like to know how to save this array in memory and read from it in another activity. I already know how to manage my RAM i'm just looking for ways to get this info there and read from it.

Thanks

Answer Source

Create a Singleton Pattern and put your array into it and you can share your array across your app instance but remember this singleton class will be destroyed with the app so will your you array inside it.

This is how a singleton is created.

class Bar {
private static class ArrayHolder {
    public static List<String> array = new ArrayList<>();
}

public static Bar getArray() {
    return array;
}
}

Whenever you need to access your array just do this ArrayHolder.getArray()