4

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

7
  • this list is static or can be changed ? Commented Mar 11, 2017 at 16:50
  • i mean can the values changes or not @Os. Commented Mar 11, 2017 at 16:52
  • Best bet is to use share preferences. Then use gson to serialize the data into a string json structure. If you just sending across activities use parceble interface for serialization. This link is excellent. developer.android.com/training/basics/data-storage/… For Gson a quick starter howtodoinjava.com/best-practices/… For parcelable survivingwithandroid.com/2015/05/… Happy reading! Commented Mar 11, 2017 at 16:53
  • 3
    Your list is already in RAM / heap. It's a Java object... Commented Mar 11, 2017 at 16:56
  • A SQL query of SELECT name FROM names WHERE name LIKE "othername" is a really cheap SQL operation, so why not do that? Commented Mar 11, 2017 at 16:57

1 Answer 1

2

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()

Sign up to request clarification or add additional context in comments.

2 Comments

What's the purpose of the ArrayHolder class here? It looks like you're trying to do the lazy holder idiom, incorrectly; but the laziness looks unnecessary.
can i get the data from the array in another activity using the singleton approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.