Reputation: 1505
I am very new to java and am making some assumptions based on what I have read, so please correct me if I am wrong.
I'm making an Android app that downloads JSON data from the SD card, which you can then search by filtering.
If I were doing this in javascript, I'd just save the data to global variable and access it whenever. But (from the little I have read), java doesn't have globals and what it does have that are similar aren't really wise to use.
So what I do now is that every time a new search begins, is I download all the data again from the SD card. But this seems horribly inefficient. I have read a little bit about Singletons and Builders and I guess maybe that's what I'm looking for (I'm really stumbling around in the dark here), but I don't really understand how to implement them in this case, or if they are in fact the best solution.
If it makes any difference, the data is never going to change while the app is running.
Could somebody give me some pointers on the best way to do this? I really just want to get the data once when the app loads, and then be able to access it whenever later. If it helps, this is the code that I use to get the data from the SD card...
public static JSONArray getArray(){
FileInputStream stream = null;
String jString = null;
File yourFile = new File("/mnt/extSdCard/app/thejson.json");
try {
stream = new FileInputStream(yourFile);
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
jString = Charset.defaultCharset().decode(bb).toString();
} catch (FileNotFoundException e) {
Log.i("err", "file not found");
}
catch (IOException e) {
Log.i("err", "IO exception");
}
try {
stream.close();
} catch (IOException e) {
Log.i("1", "IO exception");
}
try {
names = new JSONArray(jString);
} catch (JSONException e1) {
Log.i("err", "IO exception");
}
return names;
}
Upvotes: 0
Views: 269
Reputation: 1058
You can save your data in a few different ways in Java. If you want to share data amongst many different classes, you can create a variable in one class and call it public, or you can create a public static return method which returns the desired value (in this case the variable is private). A static method can be accessed regardless of whether a class contains the object which contains the method. Another way to store your data, although I do not recommend this, I recommend the static method, is to create an interface and have all classes using the data implement that interface.
Upvotes: 1
Reputation:
Just make your "names" JSON Array a member variable in your main activity and you can access it as long as your activity lives.
Upvotes: 0