Hi i need to display array of music files in listview,and when i click that music file i need play that song,i tried using below code to display songs in listview,but it showing null pointer exception in adding array to textview line,but same code working for displaying images in listview,where i did mistake any one suggest me..
public class CustomListViewExample extends Activity {
Integer[] text;
public static ArrayList<Integer> list1 = new ArrayList<Integer>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.citylist);
list1.add(R.raw.apple);
list1.add(R.raw.intro_letter_report_card);
list1.add(R.raw.intro_title_page_1);
text = list1.toArray(new Integer[list1.size()]);
ListView l1 = (ListView) findViewById(R.id.ListView01);
l1.setAdapter(new MyCustomAdapter(text));
}
class MyCustomAdapter extends BaseAdapter {
Integer[] data_image;
MyCustomAdapter() {
data_image = null;
}
MyCustomAdapter(Integer[] text) {
data_image = text;
}
#Override
public int getCount() {
return data_image.length;
}
#Override
public String getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.city_row_item, parent, false);
TextView t1=(TextView)row.findViewById(R.id.textView1);
t1.setText(""+data_image[position]);
return (row);
}
}
}
Use following code to display audio file in ListView and clicking on any one of it, plays that song
public class AudioListActivity extends Activity {
ListView musiclist;
Cursor musiccursor;
int music_column_index;
int count;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.audiolist_activity);
init_phone_music_grid();
}
private void init_phone_music_grid() {
System.gc();
String[] proj = { MediaStore.Audio.Media._ID,MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Video.Media.SIZE };
musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,proj, null, null, null);
count = musiccursor.getCount();
musiclist = (ListView) findViewById(R.id.PhoneMusicList);
musiclist.setAdapter(new MusicAdapter(getApplicationContext()));
musiclist.setOnItemClickListener(musicgridlistener);
mMediaPlayer = new MediaPlayer();
}
private OnItemClickListener musicgridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id) {
System.gc();
music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
musiccursor.moveToPosition(position);
String filename = musiccursor.getString(music_column_index);
try {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(filename);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
}
}
};
public class MusicAdapter extends BaseAdapter {
private Context mContext;
public MusicAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
TextView tv = new TextView(mContext.getApplicationContext());
String id = null;
if (convertView == null) {
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
musiccursor.moveToPosition(position);
id = musiccursor.getString(music_column_index);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
musiccursor.moveToPosition(position);
id += " Size(KB):" + musiccursor.getString(music_column_index);
tv.setText(id);
} else
tv = (TextView) convertView;
return tv;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mMediaPlayer.stop();
}
}
For NPE, seems there's no textView1 view in R.layout.city_row_item.
Regarding showing list of music files and playing them, You could refer to this exemple.
Also, I believe You need to refer to this video from 2010 IO for creation of better adapters for ListViews (because in your code You don't use convertView item).
Use sound pool to load the sounds into the memory first. This is how I'm doing it in my app Beat Shaker:
// Sound pool new instance
spool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
// Sound pool on load complete listener
spool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
Log.i("OnLoadCompleteListener","Sound "+sampleId+" loaded.");
loaded = true;
}
});
// Load the sample IDs
soundId = new int[3];
soundId[0] = spool.load(this, R.raw.clave, 1);
soundId[1] = spool.load(this, R.raw.maracas, 1);
soundId[2] = spool.load(this, R.raw.crash, 1);
Then you can call a thread from the corresponding list selection listener that runs a function similar to this:
public void Sound1(){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int streamID = -1;
do{
streamID = spool.play(soundId[0], volume, volume, 1, 0, 1f);
} while(streamID==0);
};
Related
I'm developing and application which, among other functionalities, is intended to play audio tracks. There is a navigation drawer Activity which starts up a fragment when drawer menu option is clicked. There are two fragments which play role in "media player" functionality:
TracksListFragment (ListView with song titles)
PlayerFragment (audio player)
In order to play a song, user selects one of the songs inside TracksListFragment and then PlayerFragment opens up to play that particular song.
At this point I'm able to play a song, pause it and resume. If I pause a song and try to play another song it also works fine. My setup fails when there is a song being played at the moment and I try to play different one: both tracks play simultaneously. I avoided using singleton approach as advised here
What I have tried so far:
unsetting MediaPlayer if it's object already exists
switching from MediaPlayer = new MediaPlayer(); to MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(songPath));
Can someone explain why new MediaPlayer objects are being created even though I try to get rid of existing ones, what am I doing wrong?
Here is my Fragment class for PlayerFragment:
public class PlayerFragment extends Fragment {
public String currentTrack;
private TextView currentTrackText;
private MediaPlayer mediaPlayer;
private ImageButton trackButtonPlayPause;
private Integer length;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater
.inflate(R.layout.fragment_player, container, false);
currentTrackText = (TextView) rootView.findViewById(trackTitleText);
trackButtonPlayPause = (ImageButton) rootView.findViewById(R.id.trackButtonPlayPause);
MenuActivity activity = (MenuActivity) getActivity();
String currentTrack = activity.getTrackInfoToBePlayed();
String currentPath = activity.getTrackPathToBePlayed();
currentTrackText.setText(currentTrack);
playSong(currentPath);
// Register Button Click event
trackButtonPlayPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(isPlaybackOn() == true){
Log.e("PLAYER ---> ", "Song playing->pause");
mediaPlayer.pause();
trackButtonPlayPause.setImageResource(R.drawable.icon_track_play);
length=mediaPlayer.getCurrentPosition();
}else{
Log.e("PLAYER ---> ", "Song not playing->resume");
mediaPlayer.seekTo(length);
trackButtonPlayPause.setImageResource(R.drawable.icon_pause);
mediaPlayer.start();
}
}
});
return rootView;
}
public void playSong(String songPath){
try {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(songPath);
mediaPlayer.prepare();
mediaPlayer.start();
}else{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(songPath);
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isPlaybackOn(){
AudioManager manager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
return true;
}else{
return false;
}
}
public void stopSong(){
// to be implemented
}
}
TracksListFragment:
public class TracksListFragment extends Fragment {
private int lastExpandedPosition = -1;
private ArrayList<Song> songList;
private ExpandableListView songView;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater
.inflate(R.layout.fragment_moja_muzyka, container, false);
// get the listview
expListView = (ExpandableListView) rootView.findViewById(R.id.tracks);
// query songs
songView = (ExpandableListView)rootView.findViewById(R.id.tracks);
songList = new ArrayList<Song>();
getSongList();
SongAdapter songAdt = new SongAdapter(rootView.getContext(), songList,listDataHeader,listDataChild);
songView.setAdapter(songAdt);
// Listview Group click listener
songView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Toast.makeText(getActivity().getApplicationContext(),
"Group Clicked " + listDataHeader.get(groupPosition),
Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
songView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
// hide all groups but clicked
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) {
expListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
// Listview Group collasped listener
songView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
}
});
// Listview on child click listener
songView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
return false;
}
});
return rootView;
}
public void getSongList() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
Integer audioCounter = -1;
ContentResolver musicResolver = getActivity().getContentResolver();
String fileExtension = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp3");
String sel = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String[] selExtARGS = new String[]{fileExtension};
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songCursor = musicResolver.query(musicUri, null, sel, selExtARGS, null);
if(songCursor!=null && songCursor.moveToFirst()){
//get columns
int titleColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int albumColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ALBUM);
int mimeColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.MIME_TYPE);
int fullpathColumn = songCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.DATA);
//add songs to list
do {
audioCounter++;
long thisId = songCursor.getLong(idColumn);
String thisTitle = songCursor.getString(titleColumn);
String thisArtist = songCursor.getString(artistColumn) ;
String thisAlbum = songCursor.getString(albumColumn);
String thisPath = songCursor.getString(fullpathColumn);
if(thisArtist.toLowerCase().contains("unknown")){
thisArtist = getResources().getString(R.string.textSongNoArtistAvailable);
}
if(thisAlbum.toLowerCase().contains("music")){
thisAlbum = getResources().getString(R.string.textSongNoAlbumAvailable);
}
String thisMime = songCursor.getString(mimeColumn);
listDataHeader.add(thisTitle);
List<String> songDetails = new ArrayList<String>();
songDetails.add(thisTitle);
listDataChild.put(listDataHeader.get(audioCounter), songDetails);
songList.add(new Song(thisPath,thisId, thisTitle, thisArtist, thisAlbum));
}
while (songCursor.moveToNext());
}
}
}
I am creating one application which record voice and store it in SD card. then i open
this file and want to play or some other option by clicking on that respective file.
But when i click on that list item it'd not playing. I don't understand where is the problem. Here is my code.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listofaudiorecord);
init_phone_music_grid();
}
private void init_phone_music_grid() {
System.gc();
String[] proj = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE };
musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
count = musiccursor.getCount();
musiclist = (ListView) findViewById(R.id.PhoneMusicList);
musiclist.setAdapter(new MusicAdapter(getApplicationContext()));
musiclist.setOnItemClickListener(musicgridlistener);
mMediaPlayer = new MediaPlayer();
}
private OnItemClickListener musicgridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
System.gc();
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
musiccursor.moveToPosition(position);
String filename = musiccursor.getString(music_column_index);
try {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(filename);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
}
}
};
public class MusicAdapter extends BaseAdapter {
private Context mContext;
public MusicAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
TextView tv = new TextView(mContext.getApplicationContext());
String id = null;
if (convertView == null) {
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
musiccursor.moveToPosition(position);
id = musiccursor.getString(music_column_index);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
musiccursor.moveToPosition(position);
id += " Size(KB):" + musiccursor.getString(music_column_index);
tv.setText(id);
} else
tv = (TextView) convertView;
return tv;
}
}
}
Please give me any hint.
Thanks in Advance..
How about you switch the two
musiclist.setOnItemClickListener(musicgridlistener);
mMediaPlayer = new MediaPlayer();
to this
mMediaPlayer = new MediaPlayer();
musiclist.setOnItemClickListener(musicgridlistener);
or put the MediaPlayer reference inside the onItemClick()
I followed the link for coverflow implementation
http://www.inter-fuser.com/2010/02/android-coverflow-widget-v2.html
Here with onclick event I want to play songs from sdcard , I mean on clicking each image of coverflow I want to play differnet songs from sd card
Please share your Ideas.
Help is always appreciated.
Thanks in advance.
coverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(CoverAdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
if (position == 0) {
// play song number1
} else if (position == 1) {
// play song number 2
}
}
});
I am following this code for this
public class Entertainment extends Activity {
ListView musiclist;
TextView CurrentPlying;
Cursor musiccursor;
int music_column_index;
int count;
MediaPlayer mMediaPlayer;
int seekBarState =0;
ImageButton rewindButton,playButton,forwardButton,stopButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entertainment);
list_of_media_files();
Gallery addsgallery = (Gallery) findViewById(R.id.addsgallery);
addsgallery.setAdapter(new AddsViewAdaptor(this));
rewindButton = (ImageButton) findViewById(R.id.rewind);
playButton = (ImageButton) findViewById(R.id.play);
forwardButton = (ImageButton) findViewById(R.id.forward);
stopButton = (ImageButton) findViewById(R.id.stop);
playButton.setOnClickListener(new PlayButtonListner());
rewindButton.setOnClickListener(new RewindButtonListner());
forwardButton.setOnClickListener(new ForwardButtonListner());
stopButton.setOnClickListener(new StopButtonListner());
}
class PlayButtonListner implements View.OnClickListener{
public void onClick(View v) {
try{
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}else{
mMediaPlayer.start();
}
}
catch(Exception ex){
Log.i("Exception", "Exception in mediaplayer e = " + ex);
}
}
}
public void onInit(int status) {
}
private void list_of_media_files() {
//System.gc();
String[] proj = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE };
musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
count = musiccursor.getCount();
musiclist = (ListView) findViewById(R.id.PhoneMusicList);
musiclist.setAdapter(new MusicAdapter(this));
musiclist.setOnItemClickListener(musicgridlistener);
mMediaPlayer = new MediaPlayer();
}
private OnItemClickListener musicgridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
//System.gc();
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
musiccursor.moveToPosition(position);
String filename = musiccursor.getString(music_column_index);
// CurrentPlying =(TextView) findViewById(R.id.currentSong);
//CurrentPlying.setText(music_column_index);
try {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(filename);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
}
}
};
public class MusicAdapter extends BaseAdapter {
private Context mContext;
public MusicAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
TextView tv = new TextView(mContext);
String id = null;
if (convertView == null) {
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
musiccursor.moveToPosition(position);
id = musiccursor.getString(music_column_index);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
musiccursor.moveToPosition(position);
id += " Size(KB):" + musiccursor.getString(music_column_index);
tv.setText(id);
} else
tv = (TextView) convertView;
return tv;
}
}
class RewindButtonListner implements View.OnClickListener{
public void onClick(View v) {
try{
if (mMediaPlayer.isPlaying()) {
seekBarState=mMediaPlayer.getCurrentPosition();
mMediaPlayer.seekTo(seekBarState-300);
}else{
mMediaPlayer.start();
}
}
catch(Exception ex){
Log.i("Exception", "Exception in mediaplayer e = " + ex);
}
}
}
class ForwardButtonListner implements View.OnClickListener{
public void onClick(View v) {
try{
if (mMediaPlayer.isPlaying()) {
seekBarState=mMediaPlayer.getCurrentPosition();
mMediaPlayer.seekTo(seekBarState+300);
}else{
mMediaPlayer.start();
}
}
catch(Exception ex){
Log.i("Exception", "Exception in mediaplayer e = " + ex);
}
}
}
class StopButtonListner implements View.OnClickListener{
public void onClick(View v) {
try{
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
};
}
catch(Exception ex){
Log.i("Exception", "Exception in mediaplayer e = " + ex);
}
}
}
}
first make List or array of song list from sdcard then pass song using position
coverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(CoverAdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
playSong(list[position]); <---
}
});
Ok so im making a media player app for android. everything was ok until now. so far i have a list view that shows all .mp3 files on ur sdcard(internal and external) and when playing show a music visualizer. but i cant for the life of me alphabetize the list. everything is dynamic so xml doesnt work here.
public class MusicPlayerActivity extends Activity {
ListView musiclist;
Cursor musiccursor;
int music_column_index;
int count;
private Intent aIntent;
public static String filename;
private RelativeLayout mRelativeLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init_phone_music_grid();
mRelativeLayout = new RelativeLayout(this);
setContentView(mRelativeLayout);
mRelativeLayout.addView(musiclist);
}
public void init_phone_music_grid() {
System.gc();
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ALBUM
};
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
musiccursor = managedQuery(allsongsuri, projection , selection, null, null);
count = musiccursor.getCount();
musiclist = (ListView) findViewById(R.id.PhoneMusicList);
musiclist.setAdapter(new EfficientAdapter(getApplicationContext()));
musiclist.setOnItemClickListener(musicgridlistener);
}
private OnItemClickListener musicgridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id) {
System.gc();
music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
musiccursor.moveToPosition(position);
filename = musiccursor.getString(music_column_index);
aIntent = new Intent(v.getContext(), AudioFX.class);
aIntent.getStringExtra(filename);
startActivity(aIntent);
}
};
class EfficientAdapter extends BaseAdapter {
private Context mContext;
public EfficientAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
String id = null;
TextView tv;
if (convertView == null) {
tv = new TextView(mContext.getApplicationContext());
} else{
tv = (TextView) convertView;
}
musiccursor.moveToPosition(position);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
id = musiccursor.getString(music_column_index);
tv.setText(id);
tv.setTextSize(20);
return tv;
}}}
You just need to use DEFAULT_SORT_ORDER, like this:
String sortOrder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
musiccursor = managedQuery(allsongsuri, projection , selection, null, sortOrder);
Showing the title inside the getView method won't get a alphabetized list.
Inorder to alphabetize the list get all the music titles into a String array or an ArrayList
Alphabetize them manually and pass that String array to EfficientAdapters Constructor and store it locally and use them according to the lists position.
like
class EfficientAdapter extends BaseAdapter {
private Context mContext;
private String values[];
public EfficientAdapter(Context c, String[] a) {
mContext = c;
values = a;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
String id = null;
TextView tv;
if (convertView == null) {
tv = new TextView(mContext.getApplicationContext());
} else{
tv = (TextView) convertView;
}
id = values[position];
tv.setText(id);
tv.setTextSize(20);
return tv;
}}}
Hope this helps.....
I have some audio files in a particular directory on the SD card. I need to show their names in a listview in Android, and if I want to play or delete that particular file, can I do this through that list view? How can I do it?
public class MyPerformanceArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MyPerformanceArrayAdapter(Context context, String[] values) {
super(context, R.layout.main, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
// Change the icon for Windows and iPhone
String s = values[position];
if (s.startsWith("Windows7") || s.startsWith("iPhone")
|| s.startsWith("Solaris")) {
//imageView.setImageResource(R.drawable.no);
} else {
//imageView.setImageResource(R.drawable.ok);
}
return rowView;
}
}
public class SimpleListActivity extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this, values);
setListAdapter(adapter);
}
}
This code is a simple listview. I need to fetch their names from a particular directory to adapter class. How can I do it?
If I do any changes to that particular file, these should be reflected in the listview.
public class ReadAllFilesFromPathActivity extends Activity {
/** Called when the activity is first created. */
private List<String> myList;
File file;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.mylist);
myList = new ArrayList<String>();
File directory = Environment.getExternalStorageDirectory();
file = new File( directory + "/Test" );
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listView.setAdapter(adapter); //Set all the file in the list.
}
}
you can check use following code to show a ll Audio file in listView and click of any one you play it ..
public class AudioListActivity extends Activity {
ListView musiclist;
Cursor musiccursor;
int music_column_index;
int count;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.audiolist_activity);
init_phone_music_grid();
}
private void init_phone_music_grid() {
System.gc();
String[] proj = { MediaStore.Audio.Media._ID,MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Video.Media.SIZE };
musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,proj, null, null, null);
count = musiccursor.getCount();
musiclist = (ListView) findViewById(R.id.PhoneMusicList);
musiclist.setAdapter(new MusicAdapter(getApplicationContext()));
musiclist.setOnItemClickListener(musicgridlistener);
mMediaPlayer = new MediaPlayer();
}
private OnItemClickListener musicgridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id) {
System.gc();
music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
musiccursor.moveToPosition(position);
String filename = musiccursor.getString(music_column_index);
try {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.reset();
}
mMediaPlayer.setDataSource(filename);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
}
}
};
public class MusicAdapter extends BaseAdapter {
private Context mContext;
public MusicAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
TextView tv = new TextView(mContext.getApplicationContext());
String id = null;
if (convertView == null) {
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
musiccursor.moveToPosition(position);
id = musiccursor.getString(music_column_index);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
musiccursor.moveToPosition(position);
id += " Size(KB):" + musiccursor.getString(music_column_index);
tv.setText(id);
} else
tv = (TextView) convertView;
return tv;
}
}
}
I assume you can display those files on the list correctly.
Next, Create Menu which shows Open and Delete:
public final static int MENU_OPEN = 0;
public final static int MENU_DELETE = 1;
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.add(0, MENU_OPEN, 0, "Open");
menu.add(0, MENU_DELETE, 1, "Delete");
}
Then, listen to onContextItemSelected for menu press:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
String filename = <Your File List>.get(info.position);
switch(item.getItemId()) {
case MENU_OPEN:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(filename);
intent.setDataAndType(Uri.fromFile(file), "<Your MIME Type>");
startActivity(intent);
break;
case MENU_DELETE:
File file = new File(filename);
file.delete();
break;
}
}
Finally, to monitor the directory in real time, you should implement a FileObserver.
http://developer.android.com/reference/android/os/FileObserver.html
Use a java.io.File object on the directory your files are in:
File dir = new File( "path to dir");
String[] fileNames = dir.list();
You can even use a filter if you want only some of them:
String[] fileNames = dir.list( new FilenNameFilter() {
#Override
public void accept(File dir, String name) {
return name.startWith( "Foo");
} //met
});