I am using Java to create an Android app. I have the main activity read a CSV file, create objects, and then save them into a singleton class so the rest of the activities in the app can access them easily.
This is working perfectly fine but I am not sure if there are some other ways to achieve the same result that are considered better practice, or if perhaps my solution could cause issues down the line that I am not aware of.
MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createItemObjects();
}
public void createItemObjects(){
InputStream is = getResources().openRawResource(R.raw.items_csv);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
ArrayList<Item> items = new ArrayList<Item>();
String line = "";
try {
while((line = reader.readLine())!=null) {
String[] values = line.split(",");
String img = values[0];
int imgID = getResources().getIdentifier(img , "drawable", getPackageName());
items.add(new Item(imgID, values[1], values[2]));
}
} catch (IOException e) {
Log.v("Main Activity", "Error Reading File on Line " + line, e);
e.printStackTrace();
}
ItemListHolder.getInstance().setItemsArrayList(items);
}
So as you can see, when the app launches it reads the CSV file, creates Item
objects, creates an ArrayList
to store those Item
objects, then sends it into the ItemListHolder
singleton, so that all the Activities in the app can use ItemListHolder.getInstance().getItemsArrayList()
to retrieve the ArrayList
of Item
. Each Item
is constructed with an image ID, name, and description from a line in the CSV file.
This works without any issues, but my question is: Is having your Android app create objects from a CSV file everytime it restarts considered good practice/safe to use/efficient ect, or should you be storing your objects in some other way, such as shared preferences, so that they are actually saved in memory and do not need to be created everytime the app launches and then held inside a class.
I am familiar with Java but am very new to Android so I really have no idea what other ways of saving objects may or may not exist, or what is considered good to use. Is it better to save them to the fileOutputStream? Is it better to save them to sharedPreferences? Is there some other storage method that is better?