Android Java - 传递对象列表(内存浪费)

时间:2014-06-29 08:43:58

标签: java android memory-management io

我有listSongStrings个对象。每个对象包含4 integer(标题,专辑,艺术家,路径)和list(album_id以便稍后获得专辑封面)。但是,我需要将此列表的一部分甚至整个activity传递给将播放这些歌曲的新onCreate()

但是,你是对的!那是很多记忆!我通过仅传递路径来减少它,并且在新活动的list方法中,我将读取设备上的所有歌曲,并且如果路径匹配则仅将它们添加到播放列表。这仍然需要时间,也许还需要更多的内存。

如何减少内存使用量和将public static List<Song> getSongList(List<String> pathList, Context c) { Cursor audioCursor = c.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { "*" }, null, null, Media.TITLE + " ASC"); ArrayList<Song> songsList = new ArrayList<Song>(); if (audioCursor != null) { if (audioCursor.moveToFirst()) { do { String path = audioCursor.getString(audioCursor .getColumnIndex(MediaStore.Audio.Media.DATA)); if( !pathList.contains(path) ){ //if it's not in the list, we don't want it! continue; } String title = audioCursor.getString(audioCursor .getColumnIndex(MediaStore.Audio.Media.TITLE)); String album = audioCursor.getString(audioCursor .getColumnIndex(MediaStore.Audio.Media.ALBUM)); String artist = audioCursor.getString(audioCursor .getColumnIndex(MediaStore.Audio.Media.ARTIST)); int album_id = audioCursor.getInt(audioCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); Song s = new Song(); s.setPath(path); s.setTitle(title); s.setArtist(artist); s.setAlbum(album); s.setAlbumId(album_id); songsList.add(s); } while (audioCursor.moveToNext()); } } // return songs list array return songsList; } 首歌曲从一个活动转移到另一个活动的时间?

如果将路径列表传递给新活动并按其路径读取文件(直接)的方法是个好主意,我该怎么做?到目前为止,我有这个代码,但它效率低下。它将我们在播放列表中所需文件的路径列表作为参数,并读取外部存储器上的所有歌曲。然后它会检查每首歌曲的路径是否在路径列表中,如果没有,它会继续。

{{1}}

3 个答案:

答案 0 :(得分:1)

您是否考虑过考虑一个包含静态变量的类来保存您的列表?可以从全球所有活动中获取的东西吗?

类似

public class MYClass
{
public static ArrayList<Song> Songs;

public MYClass()
{

//Load here
}




}

你可以(可选)使用SingleTon模式来防止意外错误。

答案 1 :(得分:1)

我要做的是提供一个singleton,可以在您的应用程序中的任何位置访问,只有一个数据实例存在。这是通过private构造函数和public static get(...)方法实现的,如此......

public class SongStore {

    private static SongStore sSongStore;
    private Context mContext;
    private ArrayList<Song> mSongList;

    private SongStore(Context context) {
        mContext = context;
        loadData();
    }

    public static SongStore get(Context context) {
        if (sSongStore == null) {
            sSongStore = new SongStore(context.getApplicationContext());
        }
        return sSongStore;
    }

    private void loadData() {
        // load the data
    }

    public ArrayList<Song> getSongs() { ... }
}

您可能参加过哪些活动,只需执行以下操作即可:&gt; SongStore .get(YourClass.this).getSongs();获取Song

答案 2 :(得分:0)

您可以访问ContentProvider中的歌曲,因此无需在Activities之间传递。

您所要做的就是在Array中发布onStop()首歌曲,这样当活动在后台时,它就不会保留内存。

释放我的意思是:

public void onStop(){
   this.songsList = null;
}

此外,如果你真的想将这些歌曲从一个Activity传递到另一个Activity(在一个Intent中),这个解决方案也会在这种情况下发布歌曲。

时间考虑因素:

如果生成歌曲的ArrayList确实需要很长时间,那么您可以使用其他人已经建议的Singleton概念来缓存它。但是你应该注意静态引用以避免内存泄漏。