I want to change the song with a variable but can not do that.
Button btnSpeaker = (Button)findViewById(R.id.btnSpeaker);
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer file = MediaPlayer.create(MainActivity.this , R.raw.file1);
file.start();
}
});
final MediaPlayer mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.file1);
Button btnSpeaker = (Button)findViewById(R.id.btnSpeaker);
final int[] resources={R.raw.file1,R.raw.file2};
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int resource;
//if u meant getting resource variable from the file name
resource=getApplicationContext().getResources().getIdentifier("file2","raw",getPackageName());
//or
resource=resources[index];
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(getApplicationContext().getResources().openRawResourceFd(resource).getFileDescriptor());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
Button btnSpeaker = (Button)findViewById(R.id.btnSpeaker);
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp;
mp=MediaPlayer.create(getApplicationContext(), getResources().getIdentifier(word.toLowerCase(),"raw",getPackageName()));
mp.start();
}
});
Related
iam already did add bookmark in the firebase but i dont know how can i get it
reference = FirebaseDatabase.getInstance().getReference("pagenumber");
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pagenumber = pdfView.getCurrentPage();
reference.setValue(pagenumber);
if (true) {
Toast.makeText(getApplicationContext(), "تم حفظ العلامة", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "لم يتم حفظ العلامة", Toast.LENGTH_SHORT).show();
}
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
So I made a media Player that works fine but I have one big problem, after pressing play, if I close the activity or app, the music continues to play, if I click again, the music plays on the other one, and I don't know how to fix it. I just want the music to stop after closing the activity or app without any problem.
Here is the full code:
public class m1 extends AppCompatActivity {
ImageView backm1, replay, forward, btPlay, btPause;
TextView playerPosition, playerDuration;
CircularSeekBar seekBar;
MediaPlayer mediaPlayer;
Handler handler = new Handler();
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m1);
backm1 = (ImageView) findViewById(R.id.backm1);
backm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m1.super.onBackPressed();
}
});
playerPosition = findViewById(R.id.playerPosition);
playerDuration = findViewById(R.id.playerDuration);
replay = findViewById(R.id.replay);
forward = findViewById(R.id.forward);
seekBar = findViewById(R.id.seekBar);
btPause = findViewById(R.id.btPause);
btPlay = findViewById(R.id.btPlay);
mediaPlayer = MediaPlayer.create(this,R.raw.ding_dong);
runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this,500);
}
};
int duration = mediaPlayer.getDuration();
String sDuration = convertFormat(duration);
playerDuration.setText(sDuration);
btPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
handler.postDelayed(runnable, 0);
}
});
btPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.pause();
handler.removeCallbacks(runnable);
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if(mediaPlayer.isPlaying() && duration != currentPosition){
currentPosition = currentPosition + 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
if (mediaPlayer.isPlaying() && currentPosition > 10000){
currentPosition = currentPosition - 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
seekBar.setOnSeekBarChangeListener(new CircularSeekBar.OnCircularSeekBarChangeListener() {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar, float v, boolean b) {
if (b) {
mediaPlayer.seekTo((int) v);
}
playerPosition.setText(convertFormat(mediaPlayer.getCurrentPosition()));
}
#Override
public void onStopTrackingTouch(CircularSeekBar circularSeekBar) {
}
#Override
public void onStartTrackingTouch(CircularSeekBar circularSeekBar) {
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btPause.setVisibility((View.GONE));
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
}
});
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
return String.format("%02d:%02d"
,TimeUnit.MILLISECONDS.toMinutes(duration)
,TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
I added onDestroy but I think in a wrong way and this error came out:
2021-03-08 10:13:40.843 419-4716/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags: } when converting to stream
2021-03-08 10:13:40.906 28868-28868/com.example.diligent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.diligent, PID: 28868
java.lang.IllegalStateException
at android.media.MediaPlayer.getCurrentPosition(Native Method)
I added this:
private void stopPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
And the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
Any other suggestions are welcome.
Thank you in advance.
Stop and release media resources on onDestroy of activity.
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
MediaPlayer player; //MediaPlayer object
*Function to stop media Player *
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
Call the function in onStop() callback
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
I have a problem with the Android MediaPlayer. As soon as a new sound file is clicked by user input, the old one does not stop, so all audio files overlap.
I already tried common methods like MediaPlayer.stop(); and
MediaPlayer.release();
These methods always result in an app crash, although they are called in the correct order
public void Abspielen(String Datei) {
try {
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Abspielen("filename");
}
I worked out the following solution:
public void Abspielen(String Datei) {
try {
stopKnopf = findViewById(R.id.fab2);
stopKnopf.show();
try {
if (AndreasPlayer.isPlaying()) {
AndreasPlayer.reset();
}
} catch (Exception ex) {
}
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
stopKnopf.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
AndreasPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
I'm having this error out of the blue and have no idea what's causing it or where it has come from.
Basically I've got a RecyclerView that gets populated with products. When a product is selected, I've got a custom Dialog that pops up where the user can increase product quantity or remove the product. This all works, however if I click the same product a second time it crashes the app with the following error:
System services not available to Activities before onCreate()
This is my RecyclerView.Adapter with the onBindViewHolder()
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.MyViewHolder>{
#Override
public void onBindViewHolder(#NonNull OrderAdapter.MyViewHolder holder, int position) {
final Item Item = ItemList.get(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(context,R.style.Custom_Theme_Dialog);
//Code breaks on this line
dialog.setContentView(R.layout.dialog_cart_edit);
cartProdDesc = dialog.findViewById(R.id.lblcartProdDesc);
cartQuantity = dialog.findViewById(R.id.edit_quantity);
btnDone = dialog.findViewById(R.id.btn_dialog_done);
btnRemove = dialog.findViewById(R.id.btn_dialog_remove);
addQuantity = dialog.findViewById(R.id.addition_action);
minusQuantity = dialog.findViewById(R.id.minus_action);
cartProdDesc.setText(cartItem.getProductDescription());
cartPackSize.setText(cartItem.getPackSize());
addQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(++quantity));
}
});
minusQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
quantity = Integer.parseInt(cartQuantity.getText().toString());
} catch (NumberFormatException nf) {
Log.e("Number Exception","Number Is Blank");
quantity = 0;
} catch (Exception e){
Log.e("ERROR",e.toString());
}
cartQuantity.setText(String.valueOf(--quantity));
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cartQuantity.getText().toString().isEmpty() || cartQuantity.getText().toString().equals("0") || cartQuantity.getText().toString().contains("-")){
cartQuantity.setError("Enter a valid quantity");
} else {
newQuantity = cartQuantity.getText().toString();
db.updateCartItem(new CartItem(cartItem.getId(),cartItem.getProductCode(),cartItem.getBarcode(),cartItem.getNappiCode(),cartItem.getProductDescription(),cartItem.getPackSize(),newQuantity));
updateDataSet();
notifyDataSetChanged();
dialog.dismiss();
}
}
});
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogInterface.OnClickListener dialogClickListner = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
db.deleteCartItem(cartItem.getId());
updateDataSet();
dialog.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to remove " + cartItem.getProductDescription()).setPositiveButton("Yes",dialogClickListner).setNegativeButton("No",dialogClickListner).show();
}
});
dialog.show();
}
});
}
}
I've got a private Dialog dialog; declaration further up on the Activity in case anyone was wondering.
The code breaks on the dialog = new Dialog(context,R.style.Custom_Theme_Dialog); however if I comment out the dialog.show() at the end I have no issues, apart from the dialog not showing, but that tells me that the problem isn't with the assigning of the dialog, or am I wrong on this train of thought ?
This is a line of code in my OrderActivity where I'm calling the adapter, I'm sending the context from here.
OrderAdapter = new OrderAdapter(this,ItemList);
This is my constructor where I'm assigning Context
public OrderAdapter(Context context, List<CartItem> cartItemList){
this.context = context;
this.cartItemList = cartItemList;
}
Depending on where that Context is coming from exactly, it might have already been "destroyed" by the time onClick() is called (well not really, because the Dialog is holding an implicit reference to it). In this case this is also a memory leak.
I'd suggest you to change the following:
#Override
public void onClick(View view) {
dialog = new Dialog(context, R.style.Custom_Theme_Dialog);
To this:
#Override
public void onClick(View view) {
dialog = new Dialog(view.getContext(), R.style.Custom_Theme_Dialog);
This way you'll always reference the Context the corresponding View is associated with.
There is a play button(sound review), when I hit it plays, but when I hit several times, it plays multiply.
I wanted to stop this with other topic's codes, didn't help, any idea?
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaControl.isPlaying()==true){
mediaControl.pause();
}
else
{
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.start();
}
}
});
Change your code to something like this:
boolean isPaused = true;
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isPaused){
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
}
});
mediaControl.start();
isPaused = false;
}
else
{
mediaControl.pause();
isPaused = true;
}
}
});
Don't create the mediaControl instance every time(Which makes the song to load from begining). Instead, you can initialise mediaControl to null and create an instance of it when it is null
mediaControl =null;
img_scream1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
if (mediaControl == null) {
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
}
if (mediaControl.isPlaying() == true) {
mediaControl.pause();
} else {
mediaControl.start();
}
}
});