job.answiz.com
  • 2
Votes
name

I have a song lyrics app with a list of song names and numbers that opens lyrics of selected song. It's list of more than 1000 songs names with numbers that are read by a BufferedReader from a file and placed to ArrayList that is used to make a RecyclerView width CardWidgets. Is there a way to store the genereted ArrayList in memory so the app wouldn't repeat the same process on the start? Here is some sample code:

public void setRecyclerView(final ArrayList<ExampleSong> exampleList){
    mRecycleView = findViewById(R.id.recyclerView);
    mRecycleView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(this);
    mAdapter = new ExampleAdapter(exampleList);

    mRecycleView.setLayoutManager(mLayoutManager);
    mRecycleView.setAdapter(mAdapter);

    mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
        @Override
        public void OnItemClick(int position) {
            // open new intent
            Intent intent = new Intent(MainActivity.this, SongOpened.class);
            intent.putExtra("Example item", exampleList.get(position));
            startActivity(intent);
        }
    });
}

// Read songs from file and return in array list
public ArrayList<ExampleSong> createList(String fileName) {
    BufferedReader reader = null;
    try {
        ArrayList<ExampleSong> exampleList = new ArrayList<>();
        reader = new BufferedReader(
                new InputStreamReader(getAssets().open(fileName)));

        // do reading, usually loop until end of file reading
        String mLine;
        while ((mLine = reader.readLine()) != null) {
            int begin = mLine.indexOf(" ");
            int end = mLine.length();

            String num = mLine.substring(0,begin);
            String title = mLine.substring(begin+1, end);

            exampleList.add(new ExampleSong(title,num));
        }
        reader.close();
        return exampleList;
    } catch (IOException e) {
        //log the exception
        return null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                //log the exception
            }
        }
    }

}

 

Loading data for more than 1000 songs into an arraylist for a recyclerview that probably only fits a dozen on screen at a time is pretty inefficient. Store your data in room and use paging.

  • 1
Reply Report

Imagine if every app could do it. This is a nightmare for a mobile device RAM. What you actually need is to store this data in a database instead of text file in the assets folder. You can find more details about prepopulated databases here: https://developer.android.com/training/data-storage/room/prepopulate

  • 1
Reply Report


Qries

Related Questions

Trending Tags