I want to make an e-learning android application.
I set the string data from database to a gridview item. But I want to set the onitemclick to play an audio from raw folder for every item, that contains about 40 data.
How to set that?
this is my code :
public class DaftarHuruf extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private GridView gv;
Cursor cursor;
DBHelper dbHelper;
ListAdapter list_adapter;
String audio;
MediaPlayer mp;
public DaftarHuruf() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater layoutInflater,
ViewGroup viewGroup, Bundle bundle) {
View view = layoutInflater.inflate(R.layout.fragment_daftarhuruf,
viewGroup, false);
gv = (GridView) view.findViewById(R.id.gridview);
dbHelper = new DBHelper(getActivity());
dbHelper.open();
cursor = dbHelper.getDataHuruf();
cursor.moveToFirst();
SimpleCursorAdapter list_adapter = new SimpleCursorAdapter(
getActivity(), R.layout.grid_item, cursor,
new String[] { "huruf", "romanisasi" }, new int[] {
R.id.hurufHangeul, R.id.romawi });
gv.setAdapter(list_adapter);
gv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
audio = getString(R.id.hurufHangeul);
audio.replaceAll(".MP3", "");
int i;
i = getResources().getIdentifier(audio, "raw", getActivity().getPackageName());
mp = MediaPlayer.create(getActivity(), i);
if (mp != null) {
mp.start();
} else {
Toast.makeText(getActivity(), "Data suara tidak ada",
Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
public static DaftarHuruf newInstance(int i) {
DaftarHuruf frag = new DaftarHuruf();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, i);
frag.setArguments(args);
return frag;
}
}
Replace
audio = getString(R.id.hurufHangeul);
audio.replaceAll(".MP3", "");
int i;
i = getResources().getIdentifier(audio, "raw", getActivity().getPackageName());
mp = MediaPlayer.create(getActivity(), i);
With:
mp = MediaPlayer.create(this, R.raw.*name of the audio file*);
to set up the media player to the specified sound.
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 a small music player app. I have two classes named "Tab3Tracks" and "NowPlaying". I created an ArrayList in "Tab3Tracks" class. Now, I want to access the arraylist which is loaded with songs in "NowPlaying" class. Check my code for mistakes. I am getting error in accessing ArrayList.
Tab3Tracks Class
public class Tab3Tracks extends ListFragment {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
private ArrayList<String> trackslist = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3tracks, container, false);
final String trackid = MediaStore.Audio.Media._ID;
final String trackno = MediaStore.Audio.Media.TRACK;
final String trackname = MediaStore.Audio.Media.TITLE;
final String path = MediaStore.Audio.Media.DATA;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getContext().getContentResolver();
final String[] projection = {trackid,trackno,trackname,path
};
final Cursor cursor = cr.query(uri,projection,null,null,null);
if (cursor!=null){
if(cursor.moveToFirst()){
do{
int trackIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
trackslist.add(cursor.getString(trackIndex));
}while(cursor.moveToNext());
}
} cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),R.layout.playlist_item,R.id.songTitle,trackslist
);
setListAdapter(adapter);
return v;
}
public ArrayList<String> getList(){
return trackslist;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int songIndex = position;
// Starting new intent
Intent in = new Intent(getActivity(), NowPlaying.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
getActivity().setResult(100, in);
getActivity().finish();
startActivity(in);
}
}
Is my method correct in accessing ArrayList from Another class ?
NowPlaying Class
public class NowPlaying extends AppCompatActivity{
public ArrayList<String> songsList = new ArrayList<String>();
public Tab3Tracks songs1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
// Getting all songs list
songsList= songs1.getList();
}
}
LogCat Runtime Error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.digital.thefearstuff.tfsmusicplayer.Tab3Tracks.getList()' on a null object reference
You are calling the method getlist() in a wrong way. You can get this from two methods:
1) Making Instance of the class(tab3tracks) in the class you want and then calling the method getlist().
Tab3tracks tab3 = new Tab3Tracks(); songslist = tab3.getlist();
2) Making the method static and then call it from another class without making instance of the class(tab3tracks)(which contains method getlist())
Tab3tracks.getlist();
The error that you asked is that you have not made the getlist() static and you are calling it statistically.
First Solution---
Tab3Track Class -:
public class Tab3Tracks extends ListFragment {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public ArrayList<String> trackslist = new ArrayList<>();
public Tab3Tracks(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3tracks, container, false);
final String trackid = MediaStore.Audio.Media._ID;
final String trackno = MediaStore.Audio.Media.TRACK;
final String trackname = MediaStore.Audio.Media.TITLE;
final String path = MediaStore.Audio.Media.DATA;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getContext().getContentResolver();
final String[] projection = {trackid,trackno,trackname,path
};
final Cursor cursor = cr.query(uri,projection,null,null,null);
if (cursor!=null){
if(cursor.moveToFirst()){
do{
int trackIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
trackslist.add(cursor.getString(trackIndex));
}while(cursor.moveToNext());
}
} cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),R.layout.playlist_item,R.id.songTitle,trackslist
);
setListAdapter(adapter);
return v;
}
public ArrayList<String> getList(){
return trackslist;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int songIndex = position;
// Starting new intent
Intent in = new Intent(getActivity(), NowPlaying.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
getActivity().setResult(100, in);
getActivity().finish();
startActivity(in);
}
}
NowPlaying Class:
public class NowPlaying extends AppCompatActivity{
public ArrayList<String> songsList = new ArrayList<String>();
public Tab3Tracks tab3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
// Getting all songs list
tab3 = new Tab3Tracks();
songsList= tab3.getList();
}
}
Second Solution:
Tab3Tracks Class:
public class Tab3Tracks extends ListFragment {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public ArrayList<String> trackslist = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3tracks, container, false);
final String trackid = MediaStore.Audio.Media._ID;
final String trackno = MediaStore.Audio.Media.TRACK;
final String trackname = MediaStore.Audio.Media.TITLE;
final String path = MediaStore.Audio.Media.DATA;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getContext().getContentResolver();
final String[] projection = {trackid,trackno,trackname,path
};
final Cursor cursor = cr.query(uri,projection,null,null,null);
if (cursor!=null){
if(cursor.moveToFirst()){
do{
int trackIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
trackslist.add(cursor.getString(trackIndex));
}while(cursor.moveToNext());
}
} cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),R.layout.playlist_item,R.id.songTitle,trackslist
);
setListAdapter(adapter);
return v;
}
public static ArrayList<String> getList(){
return trackslist;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int songIndex = position;
// Starting new intent
Intent in = new Intent(getActivity(), NowPlaying.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
getActivity().setResult(100, in);
getActivity().finish();
startActivity(in);
}
NowPlaying Class:
public class NowPlaying extends AppCompatActivity{
public ArrayList<String> songsList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
// Getting all songs list
songsList= Tab3Tracks.getList();
}
}
This is my code for retrieving the list of the songs on the device. I want to play the selected song. Couldn't figure out how to use the onItemClickListener to do it. How do I do that in another activity?
public class SongsFragment extends Fragment {
public SongsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_songs, container, false);
ListView audioView = (ListView)view.findViewById(R.id.songView);
ArrayList<String> audioList = new ArrayList<>();
String[] proj = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};
final Cursor audioCursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
int audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
audioList.add(audioCursor.getString(audioIndex));
} while (audioCursor.moveToNext());
}
}
audioCursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, audioList);
audioView.setAdapter(adapter);
return view;
}
Use audioView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Object song = list.getItemAtPosition(position);
//TODO play song
}
});
Basically, when you click a song item from the list view, you will just get the value of the selected song and then you can then play it.
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);
};
i am able to show all videos from sdcard into ListView but how to show only specified videos from sdcard into Listview in android.Can anybody help please?
-I am showing all videos in Listview.
-show particular video file.
This is my Code.
public class VideoStoredInSDCard extends Activity
{
private Cursor videoCursor;
private int videoColumnIndex;
ListView videolist;
int count;
String thumbPath;
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,MediaStore.Video.Thumbnails.VIDEO_ID };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialization();
}
private void initialization()
{
System.gc();
String[] videoProjection = { MediaStore.Video.Media._ID,MediaStore.Video.Media.DATA,MediaStore.Video.Media.DISPLAY_NAME,MediaStore.Video.Media.SIZE };
videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,videoProjection, null, null, null);
count = videoCursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
System.out.println("========gte Count of video List============== :" + videolist);
videolist.setAdapter(new VideoListAdapter(this.getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id)
{
System.gc();
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videoCursor.moveToPosition(position);
String filename = videoCursor.getString(videoColumnIndex);
Log.i("FileName: ", filename);
Intent intent = new Intent(VideoStoredInSDCard.this, ViewVideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
}};
public class VideoListAdapter extends BaseAdapter
{
private Context vContext;
int layoutResourceId;
public VideoListAdapter(Context c)
{
vContext = c;
}
public int getCount()
{
return videoCursor.getCount();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View listItemRow = null;
listItemRow = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
TextView txtTitle = (TextView)listItemRow.findViewById(R.id.txtTitle);
TextView txtSize = (TextView)listItemRow.findViewById(R.id.txtSize);
ImageView thumbImage = (ImageView)listItemRow.findViewById(R.id.imgIcon);
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videoCursor.moveToPosition(position);
txtTitle.setText(videoCursor.getString(videoColumnIndex));
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videoCursor.moveToPosition(position);
txtSize.setText(" Size(KB):" + videoCursor.getString(videoColumnIndex));
int videoId = videoCursor.getInt(videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Cursor videoThumbnailCursor = managedQuery(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID+ "=" + videoId, null, null);
if (videoThumbnailCursor.moveToFirst())
{
thumbPath = videoThumbnailCursor.getString(videoThumbnailCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.i("ThumbPath: ",thumbPath);
}
thumbImage.setImageURI(Uri.parse(thumbPath));
System.out.println("============Thumbnail============== :" + videoThumbnailCursor);
return listItemRow;
}
}
}
I am using other way to get the names of the files from sdcard.
I am using files concept to do this as in How to display files on the SD card in a ListView?