Android mediaplayer using uri causes app crash - android

I have been working to resolve this problem for the last three days and cannot get it working. These are the steps of my app:
Open file browser to select and audio file
Audio file is selected
Selected audio file is added to the database
from a list of items the added file is selected
a play button is pressed to play the sound file
at this point the sound file will play, however if I close the app then open it again and attempt to play the same sound file the app crashes with the following error:
FATAL EXCEPTION: main
Process: com.arcitech.developer.ultimatesoundboard, PID: 22967
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.arcitech.developer.ultimatesoundboard.activities.ItemDetailFragment$4.onClick(ItemDetailFragment.java:153)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
the filepath(uri) I am saving to the database is:
Content://com.android.providers.media.documents/document/audio%3A15790
and the code I am using is located in the onCreateView of a fragment:
MediaPlayer m;
playSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (m != null) {
m.stop();
m.release();
m = null;
}
m = MediaPlayer.create(getActivity(), Uri.parse(mItem.filePath));
m.start();
m.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer m) {
countdownTimerHandler.removeCallbacks(countdownTimerRunnable);
}
});
}
});

According to the doc for MediaPlayer.create(), it can return null if for some reason MediaPlayer cannot be created. You should be checking the return value for null every time unless you are very confident that it will not return null (but even then, do it for safety).
You may also want to check the log at the time create() is called to see if Android is leaving any clues as to why creation failed.

Related

Failed to bind to the service

On the app launch, I need to check whether a new version is available on play store or not. To check I have implemented below code in Splash screen.
private void checkNewVersionAvailability() {
appUpdateManager = AppUpdateManagerFactory.create(getApplicationContext());
appUpdateInfo = appUpdateManager.getAppUpdateInfo();
appUpdateInfo.addOnCompleteListener(new OnCompleteListener<AppUpdateInfo>() {
#Override
public void onComplete(Task<AppUpdateInfo> task) {
if (task.isComplete()) {
if (task.getResult().updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
checkVersion(task.getResult());
} else if (task.getResult().updateAvailability() == UpdateAvailability.UPDATE_NOT_AVAILABLE) {
if (StringUtils.isNullOrEmpty(ChevronApplication.deviceId)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
RegsiterDeviceHandler handler = new RegsiterDeviceHandler(SplashScreen.this);
handler.registerDevice(false);
handler.showNextScreen();
}
}, SLEEP_TIME);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new RegsiterDeviceHandler(SplashScreen.this).showNextScreen();
}
}, SLEEP_TIME);
}
}
}
}
});
During testing on the device, I didn't get the issue. These crash logs are I found from the Pre-launch report in Playstore.
> FATAL EXCEPTION: main
Process: com.mac.app, PID: 19641
com.google.android.play.core.tasks.RuntimeExecutionException: com.google.android.play.core.internal.aa: Failed to bind to the service.
at com.google.android.play.core.tasks.k.getResult(Unknown Source)
at com.chevronrenaissance.app.activity.SplashScreen$2.onComplete(SplashScreen.java:113)
at com.google.android.play.core.tasks.a.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5538)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: com.google.android.play.core.internal.aa: Failed to bind to the service.
at com.google.android.play.core.internal.q.b(Unknown Source)
at com.google.android.play.core.internal.q.a(Unknown Source)
at com.google.android.play.core.internal.s.a(Unknown Source)
at com.google.android.play.core.internal.r.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
There seems to be an issue with Google Play Core library with Android Virtual Devices. I had to add a try/catch statement so the Pre-launch testing passes. I think you may have to wrap al your AppUpdateManager calls so the exception is catched.
I was running a very similar issue using the in-app review component. It turned out one of the emulators I was developing with had not been signed into a Google Play account. You may want to ensure your emulator is signed into Google Play.
You can check task.isSuccessful().
In this case, when the task is not successful, you can get the exception use method task.getException()
Most likely that the Emulator you are using do not contain Google Play at all.
If you are running it in a emulator and if emulator is not signed for Google play, it will show the error that "PID: [6084] AppUpdateService : Failed to bind to the service."

Crash on getSystemService(Context.CAMERA_SERVICE)

I have a widget with a button that enables the camera service.
It works quite well but after some time (maybe with the home screen app exit) it loses the status (bein on or off).
I have a crash with a NullPointerException from, I believe, Context.CAMERA_SERVICE. It is really hard to reproduce and so far I haven't found the sequence that leads to the crash.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.content.ContextWrapper.getSystemService(ContextWrapper.java:714)
at com.widget.tst.Widget.CallbackWidgetService.isCameraInUse(CallbackWidgetService.java:163)
at com.widget.tst.Widget.CallbackWidgetService.startCameraInUse(CallbackWidgetService.java:242)
//** button click-->
at com.widget.tst.Widget.CameraWidgetReceiver.updateWidgetButton(CameraWidgetReceiver.java:55)
at com.widget.tst.Widget.CameraWidgetReceiver.onReceive(CameraWidgetReceiver.java:32)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3632)
at android.app.ActivityThread.-wrap18(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1975) 
at android.os.Handler.dispatchMessage(Handler.java:109) 
at android.os.Looper.loop(Looper.java:166) 
at android.app.ActivityThread.main(ActivityThread.java:7367) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
How can Context.CAMERA_SERVICE be null?
private void isCameraInUse(){
if(context == null) return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
--> line 163 mCameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
}
else{
Toast.makeText(context, "You need to run Android version "+
Build.VERSION_CODES.M+" or above",
Toast.LENGTH_SHORT).show();
return;
}
 
It looks like somewhere inside your current class (this) it's own context gets nulled, and that's why you get your NPE.
But since you have a 100% non-null context in a variable (if(context == null) return;), why don;t you use it instead of this's own context?:
mCameraManager = (CameraManager)context.getSystemService(Context.CAMERA_SERVICE);

unable to create a service

I have a music player application and untill now, it was working smoothly.
So, i learnt about Android Focus from android documentation and i thought i would try this on my app for learning purposes.
App: minimum api level :16; Maximum:26;
I basically implemented the AudioManager.OnAudioFocusChangeListener in my service class.
In it i included this code:
if(Build.VERSION.SDK_INT>=26){
mAudioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(mAudioAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(this)
.build();
int res = mAudioManager.requestAudioFocus(mAudioFocusRequest);
synchronized(mFocusLock) {
if (res == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
mPlaybackNowAuthorized = false;
} else if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mPlaybackNowAuthorized = true;
playSong();
} else if (res == AudioManager.AUDIOFOCUS_REQUEST_DELAYED) {
mPlaybackDelayed = true;
mPlaybackNowAuthorized = false;
}
}
} else if(Build.VERSION.SDK_INT<26){
int result = 0;
if (mAudioManager != null) {
result = mAudioManager.requestAudioFocus(this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
}
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mPlaybackNowAuthorized = true;
playSong();
}
}
My onAudioFocusChange(int focusChange) looks something like this:
if(Build.VERSION.SDK_INT<26){
//<26 code
}else {
//26 and above api level
}
I tried implementing audiofocus in my application and this is how i did it. The issue is when i try to run my app now , it gives me this error
unable to create a service
What's the problem with it? i think i read the documentation clearly.
Am i missing out something?
Update:
Removing the below code does make it work
else if(Build.VERSION.SDK_INT<26){
int result = 0;
if (mAudioManager != null) {
result = mAudioManager.requestAudioFocus(this,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
}
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mPlaybackNowAuthorized = true;
playSong();
}
Stacktrace:
12-18 16:27:47.740 30183-30183/com.example.tilak.imusicplay E/AndroidRuntime:
12-18 16:27:47.740 30183-30183/com.example.tilak.imusicplay E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tilak.imusicplay, PID: 30183
java.lang.RuntimeException: Unable to create service com.example.tilak.imusicplay.MusicService: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2920)
at android.app.ActivityThread.access$2000(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1458)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.example.tilak.imusicplay.MusicService.playSong(MusicService.java:239)
at com.example.tilak.imusicplay.MusicService.initMusicPlayer(MusicService.java:115)
at com.example.tilak.imusicplay.MusicService.onCreate(MusicService.java:66)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2910)
at android.app.ActivityThread.access$2000(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1458) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:5529) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) 
12-18 16:27:47.742 30183-30183/com.example.tilak.imusicplay E/MQSEventManagerDelegate: failed to get MQSService.
Whole Class Code
look your Error Msg!this is a NullPointerException. List is a null object! check you code
java.lang.RuntimeException: Unable to create service com.example.tilak.imusicplay.MusicService: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object
The problem is that your application does not initialise songs. (Sure, there is a setSongs method, but you don't call it!)
Solution: add code to initialize songs in the appropriate place. That will fix this error ...
I strongly advise you to read the Question and Answers for:
What is a NullPointerException, and how do I fix it?

streaming a mp3 from a site/server

hi guys me and a few other djs want to be able to upload our mixes to a site that could then be streamed direct in to my app. at the moment i have the files stored on google drive. they will download and then i can play via a media player. but i want the user to be able to just stream the music direct from the site..
1) what site would you suggest for uploading of the music. i have a firebase account would this be an idea or would the data from the files i upload be expensive? im on the pay as you go account type.
****EDIT
So ive found out that firebase could be a n actual viable option for doing this
2) what would be the best way to implement the code so that it streams the music direct rather than downloading it first?
****EDIT
ive found some code while trawling the internet that could make this viable but i seam to be getting a null pointer error on the setDatasource
this is my code
i have this my onchild added
final String url = dataSnapshot.child("url").getValue(String.class);
urlList.add(url);
then in my onitemclick i use
mp3url = urlList.get(i);
fetchAudioUrlFromFirebase();
finally the method for streaming the mp3
private void fetchAudioUrlFromFirebase() {
String mp3 = mp3url;
final FirebaseStorage storage = FirebaseStorage.getInstance();
storageRef = storage.getReferenceFromUrl(mp3);
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
try {
// Download url of file
final String url = uri.toString();
mMediaplayer.setDataSource(url);
// wait for media player to get prepare
mMediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mMediaplayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("TAG", e.getMessage());
}
});
}
this is my full logcat with the null pointer error
07-11 18:39:45.326 2565-2565/com.example.harrops.h20droidapp2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.harrops.h20droidapp2, PID: 2565
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(java.lang.String)' on a null object reference
at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:198)
at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:192)
at com.google.android.gms.tasks.zze$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Following line means: mMediaPlayer is null.
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.media.MediaPlayer.setDataSource(java.lang.String)'
on a null object reference
Please check mMediaplayer is initialized before onSuccess(Uri uri) method is called.
mMediaplayer = new MediaPlayer();
Q1: i have no idea about a site do this, sorry
Q2: you have to learn how to use MediaPlayer class in android and here is an example :
String link = "your link.mp3"; //usually it's ends with .mp3
Mediaplayer player = new MediaPlayer();
player.setDataSource(link);
player.prepare();//prepare to play
player.start();
Its a quick and very simple example.
You can edit this as your need.

Sinch client wont start?

I am trying to use sinch an i am having erros i dont know why an i seem to have set it well.
and it is pointing me to this part of the code which
public void that(final String name) {
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if ((getSinchServiceInterface() == null) || (!getSinchServiceInterface().isStarted())) {
getSinchServiceInterface().startClient(name);
}
}
});
}
the "getSinchServiceInterface().startClient(name);"
this is my error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.obi.thinker.logins.call.SinchService$SinchServiceInterface.startClient(java.lang.String)' on a null object reference
at com.obi.thinker.logins.tabs.Chatting$caller$1.onClick(Chatting.java:386)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5683)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I dont understand
if ((getSinchServiceInterface() != null && !getSinchServiceInterface().isStarted())) {
getSinchServiceInterface().startClient(name);
}
the callstack says:
getSinchServiceInterface() is null
And would suggest to read this:
https://stackoverflow.com/a/41477703/1979882
I was facing this issue for weeks. I literally rewrote my SinchService from scratch, removed Sinch altogether and tried starting fresh but all to no avail. It turns out I was simply initialising my call too early.
I recommend you move the code block:
if ((getSinchServiceInterface() != null || !getSinchServiceInterface().isStarted())) {
getSinchServiceInterface().startClient(name);
}
I moved mine to the very end of my onResume method and it seems to all work fine now. The reason this doesn't continually keep starting the client is because we are adding the 'if' statement to make sure it isn't already initialised.
If you find that the issue is still thrown, which was the case for me at one point, try calling it at the very end of the launch of your activity. It simply comes down to being called before your BaseActivity has a chance to initialise mSinchServiceInterface

Categories

Resources