Android - assistance with audio player - android

i am new to android development. In my app ive implemented an audio player, it plays soounds from teh sd card. i want it to play and show the list of only those audio files that i provide in a folder the app workspace (like the images we give in drawable)
here is the code. Thank you in advance
Play.java
public class Play extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selelctedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMoveingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
selelctedFile = (TextView)findViewById(R.id.selectedfile);
seekbar = (SeekBar)findViewById(R.id.seekbar);
playButton = (ImageButton)findViewById(R.id.play);
prevButton = (ImageButton)findViewById(R.id.prev);
nextButton = (ImageButton)findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if(null != cursor)
{
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.list, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selelctedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition(){
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter{
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[] { MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[] { R.id.displayname, R.id.title, R.id.duration });
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView)view.findViewById(R.id.title);
TextView name = (TextView)view.findViewById(R.id.displayname);
TextView duration = (TextView)view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double)durationInMs/1000.0)/60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.play:
{
if(player.isPlaying())
{
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
}
else
{
if(isStarted)
{
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
}
else
{
startPlay(currentFile);
}
}
break;
}
case R.id.next:
{
int seekto = player.getCurrentPosition() + STEP_VALUE;
if(seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev:
{
int seekto = player.getCurrentPosition() - STEP_VALUE;
if(seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// returning false will call the OnCompletionListener
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
if(isMoveingSeekBar)
{
player.seekTo(progress);
Log.i("OnSeekBarChangeListener","onProgressChanged");
}
}
};
}
play.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_weight="1.0"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:padding="10dip">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/selectedfile"
android:text="Not file selected"
android:textColor="#android:color/black"
android:gravity="center_horizontal"
android:singleLine="true"
android:ellipsize="middle"/>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/seekbar"
android:max="100"
android:paddingBottom="10dip"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#android:drawable/screen_background_light">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prev"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/play"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>

You need to put your music to assets directory (ie. create subfolder titled 'sounds') and then list the contents of it by method:
myContext.getAssets().list(”sounds");
Then you have to attach the asset to MediaPlayer object:
mediaPlayer.setDataSource(myContext.getAssets().openFd(soundPathInAssets));
You should also see this thread (because the bit of code I presented to you would play whole directory): Play audio file from the assets directory
EDIT: Code from example project (in case of deleting file on my dropbox):
MainActivity.java
public class MainActivity extends Activity {
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView list = (ListView) findViewById(R.id.listView1);
mMediaPlayer = new MediaPlayer();
Button playPause = (Button) findViewById(R.id.play);
playPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mControl.isPlaying()){
mControl.pause();
} else {
mControl.start();
}
}
});
try {
list.setAdapter(new MyAdapter(getAssets().list("music")));
} catch (IOException e) {
e.printStackTrace();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String path = (String) list.getAdapter().getItem(position);
try {
AssetFileDescriptor fd = getAssets().openFd("music/"+path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class MyAdapter extends BaseAdapter {
private String[] content;
public MyAdapter(String[] content){
this.content=content;
}
#Override
public int getCount() {
return content.length;
}
#Override
public Object getItem(int position) {
return content[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = new TextView(getApplicationContext());
TextView cv = (TextView) convertView;
cv.setTextSize(18);
cv.setPadding(8, 8, 8, 8);
}
TextView v = (TextView) convertView;
v.setText(content[position]);
return v;
}
}
MediaPlayerControl mControl = new MediaPlayerControl() {
public void start() {
mMediaPlayer.start();
}
public void pause() {
mMediaPlayer.pause();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mMediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
};
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+id/play"
android:background="#drawable/btn_transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="PlayPause" />
</LinearLayout>

Related

My listview does not get populated

this is my java code
whenever i run the code, no error is shown, only the seekbar and buttons are displayed when run not the list view with any items. i am running the code on my phone not emulator. please help
public class songs extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private ListView list = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingSeekbar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
#Override
public void run() {
updatePosition();
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
prevButton = (ImageButton) findViewById(R.id.prev);
nextButton = (ImageButton) findViewById(R.id.next);
list = (ListView) findViewById(android.R.id.list);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp3");
String[] selectionArgsMp3 = new String[]{mimeType};
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selectionMimeType, selectionArgsMp3, sortOrder);
if (null != cursor && cursor.moveToFirst()) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
}
cursor.close();
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected:", file);
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c, new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durataionInMin = ((double) durationInMs / 1000.0) / 60.0;
durataionInMin = new BigDecimal(Double.toString(durataionInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durataionInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekbar = false;
}
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekbar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekbar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChanged");
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Toast.makeText(getApplicationContext(), "Playing All Songs", Toast.LENGTH_LONG).show();
return true;
case R.id.two:
Toast.makeText(getApplicationContext(), "Rename The Song", Toast.LENGTH_LONG).show();
return true;
case R.id.three:
Toast.makeText(getApplicationContext(), "Adding Ringtone", Toast.LENGTH_LONG).show();
return true;
case R.id.four:
Toast.makeText(getApplicationContext(), "Choose Playlist", Toast.LENGTH_LONG).show();
return true;
case R.id.five:
Toast.makeText(getApplicationContext(), "Song deleted", Toast.LENGTH_LONG).show();
return true;
case R.id.six:
Toast.makeText(getApplicationContext(), "Songs Deleted", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is my song.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.0" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:orientation="vertical"
android:padding="10dip">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/selectedfile"
android:ellipsize="middle"
android:gravity="center_horizontal"
android:singleLine="true"
android:text="No file selcted"
android:textColor="#android:color/black"
/>
<SeekBar
android:id="#+id/seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:padding="10dip"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/screen_background_light"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prev"
android:src="#android:drawable/ic_media_previous"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/play"
android:src="#android:drawable/ic_media_play"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:src="#android:drawable/ic_media_next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
this is my listenitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/displayname"
android:ellipsize="end"
android:singleLine="true"
android:textSize="18dip"
android:textStyle="bold"
android:layout_weight="0.75" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="303dp"
android:layout_height="104dp"
android:id="#+id/title"
android:ellipsize="end"
android:singleLine="true"
android:textSize="15dip"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/duration"
android:ellipsize="end"
android:singleLine="true"
android:textSize="15dip"
/>
</LinearLayout>
</LinearLayout>
I tried your code and it works for me. Only thing is, that the list appears in the upper right corner of the screen:

How to add next song and previous song play button in audio player using android studio2.3?

I am developing an app with audio player.I want to add next song play button and previous song play button. Following is my code which is working but in this code i want to add next track play and previous track play button.Help me!!
//MainActivity.java
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private TextView selectedfile = null;
private SeekBar seekBar = null;
private MediaPlayer player = null;
private ImageButton prev = null;
private ImageButton play = null;
private ImageButton next = null;
private MediaCursorAdapter adapter = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositinRunnable = new Runnable() {
#Override
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedfile = (TextView) findViewById(R.id.selecteditem);
seekBar = (SeekBar) findViewById(R.id.seekBar);
prev = (ImageButton) findViewById(R.id.previous);
play = (ImageButton) findViewById(R.id.play);
next = (ImageButton) findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekBar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.
INTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
adapter = new MediaCursorAdapter(this, R.layout.item, cursor);
setListAdapter(adapter);
prev.setOnClickListener(OnButtonClick);
play.setOnClickListener(OnButtonClick);
next.setOnClickListener(OnButtonClick);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
currentFile = (String) v.getTag();
startPlay(currentFile);
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selectedfile.setText(file);
seekBar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekBar.setMax(player.getDuration());
play.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
play.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositinRunnable);
seekBar.setProgress(0);
isStarted = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositinRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void updatePosition() {
handler.removeCallbacks(updatePositinRunnable);
seekBar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositinRunnable, UPDATE_FREQUENCY);
}
private View.OnClickListener OnButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositinRunnable);
player.pause();
play.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
play.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.previous: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
;
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged =
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "OnProgressChanged");
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
};
}
//MediaCursorAdapter.java
public class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c, new String[]{MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.TITLE,MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(cursor.getColumnIndex(
MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(cursor.getColumnIndex(
MediaStore.MediaColumns.TITLE)));
long durationInMS = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) durationInMS / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).
setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.item, parent, false);
bindView(v, context, cursor);
return v;
}
}

Want to play video efficiently using textureview to resolve fatal signal N error

I am using videoView to play video but I am getting fatal signal 6 error so I got solution that use textureview instead of videoview but I have no idea how to use it .
This is my code.
public class MainActivity extends Activity {
ListView listview;
CustomListAdapter adapter;
private static ProgressDialog progressDialog;
public static int currentItem;
public static ArrayList<String> videoLIst;
public static MediaController mediaController ;
boolean pauseOnScroll = true;
boolean pauseOnFling = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
System.gc();
videoLIst = new ArrayList<String>();
mediaController = new MediaController(MainActivity.this);
videoLIst.add("http://journey.coderspreview.com/uploads/Home_Video/mov_bbb.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/165/video/father-and-young-daughter.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/185/video/couple-on-sail-boat.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/39/video/VID-20141231-WA0006.mp4");
videoLIst.add("http://journey.coderspreview.com/uploads/experience/26/video/VID-20141216-WA0004.mp4");
listview = (ListView) findViewById(R.id.list);
listview.setAdapter(new CustomListAdapter(this, videoLIst));
listview.setRecyclerListener(new RecyclerListener() {
#Override
public void onMovedToScrapHeap(View view) {
VideoView videoView = (VideoView)view.findViewById(R.id.VideoView);
}
});
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
private int mFirstVisibleRow = -1;
private int mActiveItem = -1;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int firstVisibleRow = listview.getFirstVisiblePosition();
if( mFirstVisibleRow != firstVisibleRow )
{
mFirstVisibleRow = firstVisibleRow;
// Cancel the video of the previous active item
VideoView prevActiveVideoView = getVideoViewForRow(mActiveItem);
if( prevActiveVideoView != null )
{
prevActiveVideoView.pause();
}
// Start the video of the new active item
mActiveItem = mFirstVisibleRow + 1;
VideoView newActiveVideoView = getVideoViewForRow(mActiveItem);
if(newActiveVideoView != null)
{
newActiveVideoView.start();
}
}
}
private VideoView getVideoViewForRow(int row)
{
int firstVisibleRow = listview.getFirstVisiblePosition();
View rowView = listview.getChildAt(row-firstVisibleRow);
return (rowView == null) ? null : (VideoView)rowView.findViewById(R.id.VideoView);
}
});
}
static class ViewHolderItem {
TextView textViewItem;
VideoView video;
ProgressBar progressbar;
}
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<String> videoList;
public CustomListAdapter(Activity activity, ArrayList<String> videoList) {
this.activity = activity;
this.videoList = videoList;
}
#Override
public int getCount() {
return videoList.size();
}
#Override
public Object getItem(int location) {
return videoList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("NewApi")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderItem viewHolder;
if (convertView == null){
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.video_list_item, null);
viewHolder = new ViewHolderItem();
viewHolder.video = (VideoView)convertView.findViewById(R.id.VideoView);
viewHolder.progressbar = (ProgressBar)convertView.findViewById(R.id.progress);
viewHolder.textViewItem =(TextView)convertView.findViewById(R.id.txvposition);
int pos;
pos=viewHolder.video.getCurrentPosition();
Log.d("current item position:",""+pos);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
viewHolder.textViewItem.setText("Video"+position);
// mediaController.setAnchorView(viewHolder.video);
Log.d("video url inadapter:", ""+videoLIst.toString());
Uri uri = Uri.parse(videoList.get(position));
// viewHolder.video.setMediaController(mediaController);
// viewHolder.video.setVideoURI(uri);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
viewHolder.video.setVisibility(View.GONE);
viewHolder.video.setVisibility(View.VISIBLE);
viewHolder.video.setVideoURI(Uri.parse(videoList.get(position)));
}
}, 200);
//viewHolder.video.start();
viewHolder.video.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer arg0) {
viewHolder.progressbar.setVisibility(View.GONE);
viewHolder.video.start();
viewHolder.video.setBackgroundResource(0);
}
});
viewHolder.video.setOnInfoListener(new OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.d("BUFFRRING START", "On_InFO");
if (MediaPlayer.MEDIA_INFO_BUFFERING_START == what) {
viewHolder.progressbar.setVisibility(View.VISIBLE);
Log.d("BUFFRRING START", "" + what);
}
if (MediaPlayer.MEDIA_INFO_BUFFERING_END == what) {
viewHolder.progressbar.setVisibility(View.GONE);
Log.d("BUFFRRING END", "" + what);
}
if (MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START == what) {
viewHolder.progressbar.setVisibility(View.GONE);
Log.d("RENDERING END", "" + what);
}
return false;
}
});
viewHolder.video.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.d("Error", "------>error" + what + "/" + extra);
if (extra != 0) {
Toast.makeText(MainActivity.this, "Can't Play Video",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
viewHolder.video.clearAnimation();
return convertView;
}
}
}
activity_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector" />
</RelativeLayout>
video_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<VideoView
android:id="#+id/VideoView"
android:layout_width="match_parent"
android:layout_height="100dp" />
<ProgressBar
android:id="#+id/progress"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
/>
<TextView
android:id="#+id/txvposition"
android:layout_width="match_parent"
android:layout_height="80dp" />
</LinearLayout>
I am facing this two proble.
1)On scroll videos/list items starts buffering again for the item that was already buffered.
2)On fast scroll list gets too laggy and get stuck and crashes.
please give me guidence how I used textureview insted of videoview.

How to implement a viewpager like below screen shot?

This is implemented in whatsapp,how to add a view(for audio) dynamically into the view pager like this.
i have implemented working example for images but how to do that when both image and audio files were there?
Any code or working example will be much appreciated.
Thank you in advance.
public class download_data_adapter extends PagerAdapter {
private Context context;
private List<Bitmap> data;
private List<String> path;
ImageButton btnplaypause;
private SeekBar seekBarProgress;
Button btnCancel;
private MediaPlayer mediaPlayer;
private PopupWindow pwindo;
private int mediaFileLengthInMilliseconds;
private final Handler handler = new Handler();
public download_data_adapter(Context c, List<Bitmap> b,List<String> s) {
context = c;
data = b;
path = s;
}
#Override
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(final ViewGroup container, int position) {
final TouchImageView imageView = new TouchImageView(context);
int padding = 5;
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageBitmap(data.get(position));
imageView.setTag(path.get(position));
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (imageView.getTag().toString().endsWith(".mp3")) {
initiatePopupWindow(imageView.getTag().toString());
}
}
private void initiatePopupWindow(final String tag) {
try {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.audio_play_layout,(ViewGroup) container. findViewById(R.id.rlAudioLayout));
pwindo = new PopupWindow(layout,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);
pwindo.showAtLocation(layout, Gravity.CENTER,0, 0);
btnCancel = (Button) layout.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaPlayer.pause();
pwindo.dismiss();
}
});
seekBarProgress = (SeekBar) layout.findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99);
seekBarProgress.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v,
MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
* sb.getProgress();
mediaPlayer
.seekTo(playPositionInMillisecconds);
}
return false;
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer .setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(
MediaPlayer arg0,
int percent) {
seekBarProgress.setSecondaryProgress(percent);
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(
MediaPlayer arg0) {
btnplaypause
.setImageResource(R.drawable.button_play);
}
});
btnplaypause = (ImageButton) layout.findViewById(R.id.btnPlayPause);
btnplaypause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer
.setDataSource(tag);
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer
.getDuration();
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
btnplaypause
.setImageResource(R.drawable.button_pause);
} else {
mediaPlayer.pause();
btnplaypause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int) (((float) mediaPlayer
.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100));
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Activity goes here:
in OnCreate i am calling async task to get the image/record's absolute paths from server,and adding those to list as of you are seeing "bitmaps" and "bitmapUrl" on post execute im adding the below code
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new download_data_adapter(context,bitmaps,bitmapUrl);
viewPager.setAdapter(adapter);
the main.xml can be
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="#+id/wrapper1"
android:layout_width="match_parent"
android:layout_height="#dimen/titlebarsize"
android:background="#color/red">
<SeekBar
android:id="#+id/progressrecord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#drawable/violetborderbox"
android:thumb="#drawable/playbtn"
android:progressDrawable="#drawable/seekbar_progress"
android:paddingLeft="35dp"
android:paddingRight="35dp"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/wrapper2"
android:layout_below="#+id/wrapper1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/violetbg"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginBottom="200dp"
app:matchChildWidth="#+id/vg_cover"
/>
</RelativeLayout>
Create an xml with the following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageone"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
/>
</LinearLayout>
and inflate this inside your adapter class
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
int[] flagone;
LayoutInflater inflater;
public ViewPagerAdapter(Context context,int[] flagsone) {
this.context = context;
this.flagone = flagsone;
}
#Override
public int getCount() {
return flag.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
ImageView imgone;
Button button;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_image, container,
false);
// Capture position and set to the TextViews
// Locate the ImageView in viewpager_item.xml
imgone = (ImageView) itemView.findViewById(R.id.imageone);
// Capture position and set to the ImageView
imgone.setImageResource(flagone[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
and in activity
onCreate(){
int imagelist1={R.drawable.image1};
int imagelist2={R.drawable.image2};
ViewPagerAdapter adapter = new ViewPagerAdapter(mContext, imagelist1,imaglist2);
// Binds the Adapter to the ViewPager
myViewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
//System.out.println("new page selected"+position);
pageposition=position;
}
#Override
public void onPageScrolled(int i, float v, int i2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
try{
imageview.setVisibility(View.GONE);
imagebutton.setVisibility(View.VISIBLE);
}
});
}

correctly displays a seekbar in custom adapter

I have a list in which each element on a player. When I click on "start" and a song starts playing strip seekbar starts moving. when click on the "stop" the song stops playing and the strip stops. But if while moving the strip I scroll list and it goes off the screen, it starts to move another strip that is on the same position in the visible area of the screen.
public class RecordAdapter extends BaseAdapter {
private MediaPlayer mediaPlayer;
private LayoutInflater inflater;
private ArrayList<RecordBean> recordBeans;
private final Handler handler = new Handler();
private Context ctx;
private int global_position;
...
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.recorditem, parent, false);
holder = new ViewHolder();
holder.date = (TextView) view.findViewById(R.id.recordate);
holder.seekBar = (SeekBar) view.findViewById(R.id.seekBar);
holder.start = (Button) view.findViewById(R.id.btnStart);
holder.stop = (Button) view.findViewById(R.id.btnStop);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.date.setText(" " + recordBeans.get(position).getDate());
holder.start.setTag(position);
holder.stop.setTag(position);
holder.seekBar.setTag(position);
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(final SeekBar seekBar, final int i, boolean b) {
if (b && (Integer)seekBar.getTag()==global_position) {
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
holder.start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
releaseMP();
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(recordBeans.get((Integer) v.getTag()).getFile());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
global_position = position;
holder.start.setTextColor(Color.RED);
holder.seekBar.setMax(mediaPlayer.getDuration());
startPlayProgressUpdater(holder.seekBar,holder.start);
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
if (mediaPlayer == null) {
return;
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
Log.d("LOG_TAG", "onCompletion");
holder.start.setTextColor(Color.WHITE);
}
});
}
});
holder.stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer == null)
return;
if ((Integer) v.getTag() == global_position) {
mediaPlayer.stop();
}
}
});
return view;
}
private void releaseMP() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static class ViewHolder {
TextView date;
SeekBar seekBar;
Button start;
Button stop;
}
public void startPlayProgressUpdater(final SeekBar seek, final Button start) {
seek.setProgress(mediaPlayer.getCurrentPosition());
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater(seek,start);
}
};
handler.postDelayed(notification, 1000);
} else {
mediaPlayer.pause();
seek.setProgress(0);
}
}
}
EDIT:
I added geter and seter in recordBean
public int getSeekPos() {
return SeekPos;
}
public void setSeekPos(int seekPos) {
SeekPos = seekPos;
}
and
holder.seekBar.setProgress(recordBeans.get(position).getSeekPos());
holder.date.setText(" " + recordBeans.get(position).getDate());
and
#Override
public void onProgressChanged(final SeekBar seekBar, final int i, boolean b) {
if (b && (Integer)seekBar.getTag()==global_position) {
// mediaPlayer.seekTo(i);
recordBeans.get(position).setSeekPos(i);
}
}
but I think it left something extra in my code
The list item is being recycled when it leaves the screen.
You could try to call this in getView:
holder.seekBar.clearFocus();
This is a tricky process, but you can do this in the following way, as I have seen that you have created a List of RecordBean class. So what you can do is you have to create a Getter Setter in RecordBean for storing the position of you SeekBar like:
public void setSeekPos(int pos) {
this.pos = pos;
}
public int getSeekPos() {
return pos;
}
In your adapter below the line
holder.date.setText(" " + recordBeans.get(position).getDate());
set the progress of seekBar like this: holder.seekBar.setProgress(recordBeans.get(position).getSeekPos());
and inside the onProgressChanged add the following line recordBeans.get(position).setSeekPos(i);
This will resolve your issue.
Please let me know if it's working or not.
Thanks

Categories

Resources