How to show a alert dialog when app is launched first time - java

I have two audio files in my app. When the app is launched the first time and when the user plays the first audio for the first time, I want to show a dialog, but afterwards never show it again.
When the user clicks OK, then only the dialog will disappear.
I have only created the XML of the dialog because I don't know how to show a layout when the app is launched the first time.
MainActivity.java here the player1 (Media Player) and play1 (ImageView as the button to play the audio) is for the first audio where the dialog has to be shown.
public class MainActivity extends AppCompatActivity {
MediaPlayer player1, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView remainingTime1, remainingTime2;
ImageView play1, play2;
int totalTime1, totalTime2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn);
play2 = findViewById(R.id.playbtn2);
// TimeLables
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
remainingTime1 = findViewById(R.id.totalTime1);
remainingTime2 = findViewById(R.id.totalTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player1.setLooping(false);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2.setLooping(false);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
player1.seekTo(progress);
seekBar1.setProgress(progress);
currentTime1.setText(createTimerLable1(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
player2.seekTo(i);
seekBar2.setProgress(i);
currentTime2.setText(createTimerLable2(i));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException ignored) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String totTime1 = createTimerLable1(player1.getDuration());
remainingTime1.setText(totTime1);
}
};
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String totTime2 = createTimerLable2(player2.getDuration());
remainingTime2.setText(totTime2);
}
};
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}

As #blackapps suggested, You will save the information about the user in SharedPreferences. You will save whether you have displayed the dialog and whether user's has played audio for first time or not.
To save or get the details from SharedPreferences,
You can follow this SO answer for storing strings, int, boolean etc.
You can follow this SO answer for storing custom objects.

Related

MediaPlayer - handler.getCurrentPosition()

The issue is with these lines
seekBar1.setProgress(player.getCurrentPosition());
and
seekBar2.setProgress(player2.getCurrentPosition());
Error
Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
also, a small request I have an issue with the handler.postDelayed can you please check this user question too I have the same issue, here is the link to that question
Code // full code is belove this
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
Full Code // the code can be a little confusing and written badly
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.dog_howl);
player2 = MediaPlayer.create(this, R.raw.dog_bark);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
player.seekTo(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
player2.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.dog_howl);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
player = null;
}
break;
case R.id.playbtn2:
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.dog_bark);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
}
Enter this code:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.bekhayali);
player2 = MediaPlayer.create(this, R.raw.hawabanke);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.seekTo(seekBar.getProgress());
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player2.seekTo(seekBar.getProgress());
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.bekhayali);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
handler1.removeCallbacks(updateSeekBar1);
player = null;
}
break;
case R.id.playbtn2:
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.hawabanke);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
handler2.removeCallbacks(updateSeekBar2);
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}}

Media Player - Seek bar and Time lable is not progressing

IDK why but after just coping the entier mainactivty.java file from this video
IDK why my seek bar and timetable are not showing any progress
there is an exception I have 2 audio files but the video show has only one so I have doubled all the methods also the onClick and a dialog which is different from it
MainActivity.java
public class MainActivity extends AppCompatActivity {
MediaPlayer player1;
MediaPlayer player2;
SeekBar seekBar1;
SeekBar seekBar2;
TextView elapsedTimeLable1;
TextView elapsedTimeLable2;
TextView remainingTimeLable1;
TextView remainingTimeLable2;
ImageView play1;
ImageView play2;
int totalTime1;
int totalTime2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn1);
play2 = findViewById(R.id.playbtn2);
// TimeLables
elapsedTimeLable1 = findViewById(R.id.cTime1);
elapsedTimeLable2 = findViewById(R.id.cTime2);
remainingTimeLable1 = findViewById(R.id.tTime1);
remainingTimeLable2 = findViewById(R.id.tTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player1.setLooping(true);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player2.setLooping(true);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
if (fromUser1) {
player1.seekTo(progress1);
seekBar1.setProgress(progress1);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
if (fromUser2) {
player2.seekTo(progress2);
seekBar2.setProgress(progress2);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Thread (Update SeekBar & TimeLabel)
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException e) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException e) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Caution dialog
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
boolean firstStart = preferences.getBoolean("firstStart", true);
if (firstStart) {
showDialog();
}
}
// Caution dialog
private void showDialog() {
new AlertDialog.Builder(this)
.setTitle("Caution!")
.setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create().show();
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
private Handler handler1 = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String elapsedTime1 = createTimerLable1(currentPosition1);
elapsedTimeLable1.setText(elapsedTime1);
String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
remainingTimeLable1.setText("- " + remainingTime1);
}
};
private Handler handler2 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String elapsedTime2 = createTimerLable2(currentPosition2);
elapsedTimeLable2.setText(elapsedTime2);
String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
remainingTimeLable2.setText("- " + remainingTime2);
}
};
public String createTimerLable1(int duration) {
String timerLabel1 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel1 += min + ":";
if (sec < 10) timerLabel1 += "0";
timerLabel1 += sec;
return timerLabel1;
}
public String createTimerLable2(int duration) {
String timerLabel2 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel2 += min + ":";
if (sec < 10) timerLabel2 += "0";
timerLabel2 += sec;
return timerLabel2;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}
So well why should threads sleep 1000000000 milliseconds.
In that case your thread does its tasks every 1000000 seconds.
1000000000 ms => 1000000 sec => 16666 min => 277 hour
So your thread does its task every 277 hours.
The param of sleep is millisecond so put st like 1000(1 second) or something like that which is a lot shorter.
If this wasn't solution let me know.
Replace Thread.sleep(1000000000) to Thread.sleep(1000) because you just need to update text and seek bar every second
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}).start();

How to atomatically post data when any new item add in recycler view

I am trying to post data when any new Item add in recycler view it automatically post
I have already tried on item click it working fine but i want to post automatically when any item add in recycler view
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
public ArrayList<String> songNames;
Context context;
// MediaPlayer mediaPlayer = new MediaPlayer();
boolean wasPlaying = false;
Handler seekHandler = new Handler();
Runnable run;
public RecyclerViewAdapter(ArrayList<String> songNames, Context context) {
this.songNames = songNames;
this.context = context;
}
#NonNull
#Override
public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.record_card, parent, false);
return new MyViewHolder(listItem);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewAdapter.MyViewHolder holder, final int position) {
holder.textView.setText(songNames.get(position));
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.playerCard.setVisibility(View.VISIBLE);
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
Toast.makeText(context, "Internet is working", Toast.LENGTH_SHORT).show();
connected = true;
postingData(position, holder);
if (connected == true ) {
}
}
else{
connected = false;
Toast.makeText(context, "net not", Toast.LENGTH_SHORT).show();
}
}
});
holder.cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.playerCard.setVisibility(View.VISIBLE);
}
});
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(CallRecoding.songs.get(position));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
holder.seekBar.setMax(mediaPlayer.getDuration());
holder.seekBar.setTag(position);
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
holder.seekBarHint.setText("0:00/" + calculateDuration(mediaPlayer.getDuration()));
holder.playsong.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
holder.pauseRec.setVisibility(View.VISIBLE);
holder.playsong.setVisibility(View.INVISIBLE);
holder.playsong.setText(" Pause ");
run = new Runnable() {
#Override
public void run() {
// Updateing SeekBar every 100 miliseconds
holder.seekBar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 100);
//For Showing time of audio(inside runnable)
int miliSeconds = mediaPlayer.getCurrentPosition();
if (miliSeconds != 0) {
//if audio is playing, showing current time;
long minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds);
long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
if (minutes == 0) {
holder.seekBarHint.setText("0:" + seconds + "/" + calculateDuration(mediaPlayer.getDuration()));
} else {
if (seconds >= 60) {
long sec = seconds - (minutes * 60);
holder.seekBarHint.setText(minutes + ":" + sec + "/" + calculateDuration(mediaPlayer.getDuration()));
}
}
} else {
//Displaying total time if audio not playing
int totalTime = mediaPlayer.getDuration();
long minutes = TimeUnit.MILLISECONDS.toMinutes(totalTime);
long seconds = TimeUnit.MILLISECONDS.toSeconds(totalTime);
if (minutes == 0) {
holder.seekBarHint.setText("0:" + seconds);
} else {
if (seconds >= 60) {
long sec = seconds - (minutes * 60);
holder.seekBarHint.setText(minutes + ":" + sec);
}
}
}
}
};
run.run();
} else {
mediaPlayer.pause();
holder.pauseRec.setVisibility(View.INVISIBLE);
holder.playsong.setVisibility(View.VISIBLE);
holder.playsong.setText(" Play ");
}
}
});
holder.pauseRec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.pause();
holder.playsong.setVisibility(View.VISIBLE);
holder.pauseRec.setVisibility(View.GONE);
}
});
}
private void postingData(final int position, final MyViewHolder holder) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final String value = preferences.getString("user_id", "0");
String currentTime = preferences.getString("currentDate", "1");
SharedPreferences sp = context.getSharedPreferences("MyPrefs", MODE_PRIVATE);
String name = sp.getString("prospectNumber", "0");
System.out.println("pressssss"+name);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", songNames.get(position),
RequestBody.create(MediaType.parse("application/octet-stream"),
new File(CallRecoding.songs.get(position))))
.addFormDataPart("user_id", value)
.addFormDataPart("file_name", "Call Recording")
.addFormDataPart("creation_datetime", currentTime)
.addFormDataPart("prospect_number","1234567891")
.addFormDataPart("call_type","incoming")
.build();
Request request = new Request.Builder()
.url("http://159.65.145.32/api/file/upload/")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
String json = response.body().string();
System.out.println("FileUploading >>> " + json);
}
}
});
}
#Override
public int getItemCount() {
return songNames.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView, seekBarHint;
TextView playsong, pauseRec;
public static SeekBar seekBar;
CardView playerCard, cardView1;
ImageView recdonpost,notdone;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.card_item);
playsong = itemView.findViewById(R.id.recplay);
seekBarHint = itemView.findViewById(R.id.songDur);
seekBar = itemView.findViewById(R.id.seekbar);
playerCard = itemView.findViewById(R.id.playerCard);
cardView1 = itemView.findViewById(R.id.layout1);
pauseRec = itemView.findViewById(R.id.recPause);
}
}
private String calculateDuration(int duration) {
String finalDuration = "";
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration);
if (minutes == 0) {
finalDuration = "0:" + seconds;
} else {
if (seconds >= 60) {
long sec = seconds - (minutes * 60);
finalDuration = minutes + ":" + sec;
}
}
return finalDuration;
}
}
Here is my Recycler view adapter code
I want to post automatically data when data will add in recycler view
When you updating songNames in your adapter just match difference and post data for items which are new in the list
You need to make a method like this in your adapter.
void addItem(String songName){
datas.add(songName); // Add new Item into the data list in your Adapter.
notifyDataSetChanged();
}
And call this on the activity like this:
adapter.addItem(name);
Then, it will automatically changes.
You need separation of concerns.
Your RecyclerView and Adapter is part of your view component. It should not have any logic regarding network callbacks.
If you want to make a request when a new item is added, please check where you are adding the item to the list and calling notifyDatasetChanged(). Ideally, your app should make the network call there (or before adding the item to the list).
When you do this, the code would have the exact items that are being added so you would make an API call for that. Depending on bind method is not reliable as it gets called multiple times when user scrolls the list.

How to use SeekBar in RecyclerView's Adapter?

I'm getting some MP3 files from an API and showing them in the recyclerView by mediaPlayer and SeekBar. Everything works fine But there are 2 problems:
The mediaPlayer.setOnCompletionListener Doesn't work .
The Seekbar Doesn't work at all , it has no functionality , it doesn't move and the seekBar.setOnSeekBarChangeListener doesn't
work. I have used the Timer class and my TextView Which is supposed
to show current time of the mediaPlayer works properly in timer ,
but seekBar does not !
I have tried every possibility to fix the problem but I couldn't.
Here is my code for the ViewHolder :
private MediaPlayer mediaPlayer;
private SeekBar seekBar;
private TextView currentTime;
private Timer timer;
private ProgressBar progressBar;
private SimpleDraweeView artistProfile;
private SimpleDraweeView socialNetworkTypeImage;
private TextView artistName;
private TextView postReleaseDate;
private TextView likes;
private String urlMp3;
private View playButtonContainer;
private ImageView playButton;
private ImageView pauseButton;
private int mediaPlayerDuration;
private Handler seekHandler = new Handler();
TelegramVoiceViewHolder(#NonNull View itemView) {
super(itemView);
seekBar = itemView.findViewById(R.id.sb_news_feed_items_telegram_voice_seekbar);
currentTime = itemView.findViewById(R.id.tv_news_feed_items_telegram_voice_time);
progressBar = itemView.findViewById(R.id.iv_news_feed_items_telegram_voice_progress_bar);
artistProfile = itemView.findViewById(R.id.sdv_news_feed_telegram_voice_artist_profile);
socialNetworkTypeImage = itemView.findViewById(R.id.sdv_news_feed_telegram_voice_social_type);
artistName = itemView.findViewById(R.id.tv_news_feed_items_telegram_voice_artist_name);
postReleaseDate = itemView.findViewById(R.id.tv_telegram_voice_page_timer);
likes = itemView.findViewById(R.id.tv_news_feed_items_telegram_voice_post_likes);
playButtonContainer = itemView.findViewById(R.id.rl_news_feed_items_telegram_voice_play_button);
playButton = itemView.findViewById(R.id.iv_news_feed_items_telegram_voice_play_button_image);
pauseButton = itemView.findViewById(R.id.iv_news_feed_items_telegram_voice_pause_button_image);
}
private void onBindViews(DataItem dataItem) {
urlMp3 = dataItem.getAttachment().get(0).getFile();
artistProfile.setImageURI(Uri.parse(dataItem.getUser().getAvatar()));
socialNetworkTypeImage.setImageURI(Uri.parse(TELEGRAM_ICON));
socialNetworkTypeImage.setCropToPadding(true);
socialNetworkTypeImage.setAdjustViewBounds(true);
postReleaseDate.setText(TimeAgo.getTimeAgo(Long.parseLong(dataItem.getDate())));
likes.setText(dataItem.getLikes() + " People Liked This");
artistName.setText(dataItem.getUser().getName());
}
private void setUpMediaPlayer() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(context, Uri.parse(urlMp3));
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(mediaPlayer -> {
setUpMediaPlayerElements();
progressBar.setVisibility(View.GONE);
playButton.setVisibility(View.VISIBLE);
timer = new Timer();
timer.schedule(new MainTimer(), 0, 1000);
});
mediaPlayer.setOnCompletionListener(mp -> {
pauseButton.setVisibility(View.GONE);
playButton.setVisibility(View.VISIBLE);
mp.seekTo(0);
});
} catch (IOException e) {
e.printStackTrace();
}
}
private void setUpMediaPlayerElements() {
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playButtonContainer.setOnClickListener(view -> {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
pauseButton.setVisibility(View.GONE);
playButton.setVisibility(View.VISIBLE);
} else {
mediaPlayer.start();
pauseButton.setVisibility(View.VISIBLE);
playButton.setVisibility(View.GONE);
}
});
}
private String formatDuration(long duration) {
int seconds = (int) (duration / 1000);
int minutes = seconds / 60;
seconds %= 60;
return String.format(Locale.ENGLISH, "%02d", minutes) + ":" + String.format(Locale.ENGLISH, "%02d", seconds);
}
private class MainTimer extends TimerTask {
#Override
public void run() {
((Activity) context).runOnUiThread(() -> {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
mediaPlayer.setOnBufferingUpdateListener((mp, percent) -> seekBar.setSecondaryProgress((percent * mp.getDuration()) / 100));
currentTime.setText(formatDuration(mediaPlayer.getCurrentPosition()));
});
}
}
}
and then I call the onBindViews method in the onBindViewHolder :
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
DataItem data = dataItems.get(i);
if (data != null) {
((TelegramVoiceViewHolder) viewHolder).onBindViews(data);
((TelegramVoiceViewHolder) viewHolder).setUpMediaPlayer();
break;
}

Fixing a seekbar on my Android music player

I've created a simple music player in Android which has a seekbar which displays the current position in the song playing. The forward, rewind, play and pause functions work correctly. What I am trying to do is have the seekbar actually move the position within the song. (at present the seekbar does not change the position within the song. Heres my code
public class MusicPlayerA extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2500, backwardTime = 2500;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.musicplayerview);
//initialize views
initializeViews();
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.pause();
if (isFinishing()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Druids Ad");
seekbar.setMax((int) finalTime);
seekbar.setClickable(true);
}
// play mp3 song
public void play(View view) {
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaining
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// handler for back button used on music player screen
public void BackButton2 (View view) {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mus = new Intent (this, Music.class);
startActivity(mus);
}
// handler for home button used on all screens
public void BackButton (View view) {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mn = new Intent (this, Music.class);
startActivity(mn);
}
}
Its easy. Follow these steps :-
Add a seek bar change Listener.
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int seeked_progess;
#Override
public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
seeked_progess = progress;
seeked_progess = seeked_progess * 1000;
if (fromUser) {
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Now in if(fromUser), U need to add the implementation.
if (fromUser) {
Runnable mRunnable = new Runnable() {
#Override
public void run() {
int min, sec;
if (mediaPlayer != null /*Checking if the
music player is null or not otherwise it
may throw an exception*/) {
int mCurrentPosition = seekBar.getProgress();
min = mCurrentPosition / 60;
sec = mCurrentPosition % 60;
Log.e("Music Player Activity", "Minutes : "+min +" Seconds : " + sec);
/*currentime_mm.setText("" + min);
currentime_ss.setText("" + sec);*/
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();}
At last add this in onStopTrackingTouch()
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seeked_progess);
}
});
Note :-
mHandler in a global variable.
Initialize it as follows.
Handler mHandler = new Handler();
Secondly currentime_mm and currentime_ss are text views which display the current seek time of the seek bar.
and most Important,
dont forgot to add these when a song starts
seekBar.setProgress(0);// To set initial progress, i.e zero in starting of the song
seekBar.setMax(mediaDuration);// To set the max progress, i.e duration of the song
Put this code inside onCreate() method
seekbar.setMax(mediaPlayer.getDuration());
seekbar.setProgress(mediaPlayer.getCurrentPosition());
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run()
{
seekbar.setProgress(mediaPlayer.getCurrentPosition());
}
},0,1000);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
{
mediaPlayer.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
What Punam did is good but add a condition in your "onProgressChanged" function like this:
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
{
if(b)
mediaPlayer.seekTo(i);
}

Categories

Resources