我在 AsyncTask 中获取设备上的所有歌曲。当我在List 变量中的Log
所有歌曲都显示出来时。但是当我在它们的构造函数中时,它总是空的。这怎么可能?songs
AsyncTask
Log
ArrayAdapter
异步任务:
private class SongFinder extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
ContentResolver resolver = activity.getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = resolver.query(uri, projection, selection, null, null);
Log.i(TAG, "Fetching next batch of songs");
if (cursor == null) {
Toast.makeText(activity, "Failed to discover songs",
Toast.LENGTH_LONG).show();
} else if (!cursor.moveToFirst()) {
Toast.makeText(activity, "No media on device",
Toast.LENGTH_LONG).show();
} else {
cursor.moveToFirst();
while (cursor.moveToNext()) {
String id = cursor.getString(0);
String title = cursor.getString(2);
String artist = cursor.getString(1);
String data = cursor.getString(3);
String albumName = cursor.getString(8);
Long albumId = cursor.getLong(6);
String albumKey = cursor.getString(7);
songs.add(new Song(id, title, artist, data, albumName,
albumKey, albumId));
}
}
cursor.close();
// HERE IT'S FULL WITH THE SONGS I WANT
Log.d(TAG, songs.toString());
return null;
}
@Override
protected void onPostExecute(Void result) {
if (songs.size() > 0) {
//HERE IT IS ALWAYS EMPTY
Log.d(TAG, songs.toString());
SongArrayAdapter adapter = new SongArrayAdapter(activity, songs);
EndlessSongAdapter songAdapter = new EndlessSongAdapter(activity,
adapter, R.layout.arrayadapter_songs);
songsList.setAdapter(songAdapter);
songsList.setTextFilterEnabled(true);
songsList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> root, View view,
int position, long when) {
Intent newSong = new Intent(MusicService.ACTION_NEW);
newSong.putExtra("song", songs.get(position));
Log.i(TAG, "sending broadcast");
bManager.sendBroadcast(newSong);
// Reset the play/pause button.
activity.resetButton();
Intent addSong = new Intent(
"com.xx.xx.ADDSONG");
addSong.putExtra("song", songs.get(position));
bManager.sendBroadcast(addSong);
activity.fragmentChangeNewSong();
}
});
}
}
}
编辑
调用异步任务
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
activity = (MusicActivity) getActivity();
bManager = LocalBroadcastManager.getInstance(activity);
ListView songsList = getListViewWithSongs(activity);
return songsList;
}
public ListView getListViewWithSongs(final MusicActivity activity) {
songsList = new ListView(activity);
new SongFinder().execute();
return songsList;
}
所以这个private List<Song> songs
变量在doInBackground()
AsyncTask的方法里面是填的,但是在onPostExecute()
.