My app crash only in vivo phones, and the error log is this:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Context.getOpPackageName()' on a
null object reference at
android.media.PlayerBase.PlaybackDetectionCallBack(PlayerBase.java:348)
at android.media.PlayerBase.baseStop(PlayerBase.java:229) at
android.media.MediaPlayer$2.onCompletion(MediaPlayer.java:3578) at
android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:3351)
at android.os.Handler.dispatchMessage(Handler.java:106) at
android.os.Looper.loop(Looper.java:192) at
android.app.ActivityThread.main(ActivityThread.java:6671) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:818)
I believe it is about MediaPlayer which I use to play BGM in my app.
But I can't find out how this happens since the error stack didn't retrieve to my code.
Here is all my code about play BGM.
public void playBgm(final int resId, boolean restartIfSame) {
if(resId == currentBgmRes && !restartIfSame) {
if(!bgmPlayer.isPlaying()) {
bgmPlayer.start();
}
return;
}
if(bgmPlayer.isPlaying()) {
bgmPlayer.stop();
}
_playBgm(resId);
}
private void _playBgm(int resId) {
bgmPlayer.release();
bgmPlayer = MediaPlayer.create(this, resId);
bgmPlayer.setLooping(true);
currentBgmRes = resId;
bgmPlayer.start();
}
The two functions are inside class AppDelegate extends Application, so this should be the application instance.
It doesn't always crash. Since the phone causing the problem is some far-away user's, I can't get the phone in several days. So I'm not sure in what situation it will happen, but it should not happen in any situation.
I figured out the problem.
My MediaPlayer variable has an initial value new MediaPlayer().
When the Activity playing the BGM calls onPause(), I call MediaPlayer.pause().
But calling pause() to a new MediaPlayer() seems to cause crash in some devices, while OK in other devices.
I change the initial value to null, and do the null check whenever I use the object. The crash never happen again.
Related
I found this question was marked as duplicate for one about how to prevent Null Pointer Exceptions. For clarification, the problem is that the library is throwing it. My variable isn't null. More specific help about the library is more helpful.
I am creating an app for playing music. I am trying to make use of the MediaController class to add controls to the song being played. However, when I run the .show() function, I get a Null Pointer Exception.
Here is the code for the MediaController:
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
MediaController timer = view.findViewById(R.id.song_progress);
timer.setMediaPlayer(new MediaController.MediaPlayerControl() {
#Override
public void start() {
MainActivity.playingSong.start();
}
#Override
public void pause() {
MainActivity.playingSong.pause();
}
#Override
public int getDuration() {
return MainActivity.playingSong.getDuration();
}
#Override
public int getCurrentPosition() {
return MainActivity.playingSong.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
MainActivity.playingSong.seekTo(pos);
}
#Override
public boolean isPlaying() {
return MainActivity.playingSong.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return MainActivity.playingSong.getAudioSessionId();
}
});
timer.setAnchorView(view);
timer.setEnabled(true);
timer.show();
}
Here is the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.luner.mobilemusic, PID: 2021
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.measure(int, int)' on a null object reference
at android.widget.MediaController.updateFloatingWindowLayout(MediaController.java:173)
at android.widget.MediaController.show(MediaController.java:363)
at android.widget.MediaController.show(MediaController.java:314)
at com.luner.mobilemusic.Playlist$Song$PlayFragment.onViewCreated(Playlist.java:271)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:892)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
Why is this happening? Is there a good way to fix this, or should I use a different class completely? I would very much appreciate any code examples you might have.
Also, I found that removing the setAnchorView(view) prevented the error, but then caused no MediaController to appear.
Edit
After doing a more thorough search, I found two things:
The line numbers aren't accurate for some reason; the line for updateFloatingWindowLayout appeared inside a different method.
The culprit is the mDecor variable, which while running the setAnchorView method is set to the view variable. However, the view variable can't be null, as that would have caused an exception before getting to the show function. Thus, I still can't quite figure out the source of this ... the mDecor variable must somewhere be set to null, but only when I add a custom anchor view.
Edit 2
I have made lots of changes to the program at this point, so I am unable to test if a solution works. However, feel free to post an answer to help anyone else with the issue. I will accept any answer with a good amount of upvotes, as the upvotes signify that the solution worked. Thanks to everyone who tried to help!
The problem occurs when I call putString to SharedPreference.
My program is first run through TileService which runs a ForegroundService then from ForegroundService opens an Activity and in this Activity I call putString to a SharedPreference.
How to make it work perfectly?
TileService
...
#Override
public void onClick()
{
super.onClick();
Intent intent = new Intent(mContext,AdzanService.class);
if(mTileEnabled)
intent.setAction("STOP_SERVICE");
else
intent.setAction("START_SERVICE");
startForegroundService(intent);
mTileEnabled = !mTileEnabled;
}
...
Service
...
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent.getAction().equals("STOP_SERVICE"))
{
stopForeground(true);
stopSelf();
}
...
Activity
...
private void save(){
mEditor.putString("setting_location",((EditText)findViewById(R.id.setting_location)).getText().toString());
mEditor.putString("setting_times",((RadioButton)findViewById(((RadioGroup)findViewById(R.id.setting_times)).getCheckedRadioButtonId())).getTag().toString());
mEditor.apply();
}
...
Error
java.lang.RuntimeException: Unable to start service in.blackant.adzan.AdzanService#873299c with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3722)
at android.app.ActivityThread.access$1600(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1686)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6693)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at in.blackant.adzan.AdzanService.onStartCommand(AdzanService.java:97)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3703)
... 8 more
As the error message states, the Intent in your service class is null when you call intent.getAction()
Intent is nullable here according to the docs
The Intent supplied to Context.startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.
Adding a null check before you check getAction() will fix the crash, but you might want to look into why your service is being restarted
Moved methods that broadcast intents or start activities (Launch Google Assistant, Volume Up/Down, pause audio) from Service to a separate java class in order to call them using invoke and a string as their name rather than using countless of if statements (the methods are triggered upon a button press from a bluetooth device).
I am getting a NullPointerException Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.content.Context.sendBroadcast(android.content.Intent)' on a
null object reference
10-19 16:53:25.277 8073-8133/com.example.android.zeno W/System.err:
at
android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:396)
The Java class extends the Service where the methods were previously located.
This is one of the methods (triggers Google Assistant) located in a separate class called ActionsPhonecontrol:
public class ActionsPhonecontrol extends BluetoothLeService {
boolean PCL_googleNow() {
startActivity(new Intent(Intent.ACTION_VOICE_COMMAND).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
return true;
}
This is the method that invokes the other methods from the separate class:
void invokeAction(String method, String className) {
broadcastUpdate(method);
String mType = getPackageName() + "." + className;
//trigger received sound
soundPlay(R.raw.blip1, 500);
try {
Class mClass = Class.forName(mType);
Method mMethod = mClass.getMethod(method);
Object newClass = mClass.newInstance();
String p = (String) mMethod.invoke(newClass);
} catch (Exception e) {
e.printStackTrace();
}
}
Any ideas why it shows the error?
I'm loading a picture from a url into a bitmap. This code below worked on previous classes that extended Fragment. This time, I'm just copying the code and trying to use it in a class that extends AppCompatActivity. The only difference is how I'm getting context.
public void loadBitmap(String url) {
if (loadtarget == null) loadtarget = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
handleLoadedBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
mContext = MyActivity.this;
Picasso.with(mContext).load(url).into(loadtarget); //giving me null
}
In the original code, where I used it in a Fragment, I had it as
Picasso.with(getActivity()).load(url).into(loadtarget);
So now, since this class extends AppCompatActivity, I thought I could use "this" or MyActivity.this but that didn't work. I've tried initializing a Context variable "mContext" in onCreate and right before I load the image into the bitmap (like above) but neither worked. I've tried this.getApplicationContext() and I've also tried to pass mContext as a parameter in the loadBitmap() method but that didn't work either.
My URL string is correct. I'm just not sure how to tackle this problem after trying, what seems like, everything.
Last piece of information, the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:112)
at com.salty.seas.Driver.MyActivity.loadBitmap(MyActivity.java:144)
at com.salty.seas.Driver.MyActivity$1.onKeyEntered(MyActivity.java:61)
at com.firebase.geofire.GeoQuery$2.run(GeoQuery.java:126)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
In the comments to the question you said that the activity, the loadBitmap() belongs to, you actually instantiate yourself (in some other fragment) and use it as an utility class.
You should never create activites manually as they are managed by android and they have a lifecycle android maintains.
In your case the activity is not in a correct state (one of its internal fields is null), that's why you get NPE.
For utility methods create utility classes and call those from wherever you want.
I am making a remote display for a gallery app and I am getting a very strange error that seems unrelated to the cast at all. At first, it crashed because of an invalid App ID, but after registering it, and getting an App ID, it crashes and says that the selector must not be null, but the Cast part is not in the same code that calls Null. Any help?
//Inside of OnCreate
MediaRouter = MediaRouter.getInstance(getApplicationContext());
MediaRouteSelector mMediaRouteSelector = new MediaRouteSelector.Builder()
.addControlCategory( CastMediaControlIntent.categoryForCast(getString(R.string.cast_sdk_id)))
.build();
//Inside of OnCreateOptionsMenu
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_viewer, menu);
if (mAdapter.getEntries().size() > 0) {
MediaEntry currentEntry = mAdapter.getEntries().get(mCurrentPosition);
if (currentEntry == null || currentEntry.isVideo()) {
menu.findItem(R.id.print).setVisible(false);
menu.findItem(R.id.edit).setVisible(false);
menu.findItem(R.id.set_as).setVisible(false);
} else {
menu.findItem(R.id.print).setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT);
menu.findItem(R.id.edit).setVisible(true);
menu.findItem(R.id.set_as).setVisible(true);
}
}
menu.findItem(R.id.slideshow).setVisible(!mAllVideos && mSlideshowTimer == null);
MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
MediaRouteActionProvider mediaRouteActionProvider =
(MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouteMenuItem);
mediaRouteActionProvider.setRouteSelector(mMediaRouteSelector);
return super.onCreateOptionsMenu(menu);;
java.lang.IllegalArgumentException: selector must not be null
at android.support.v7.app.MediaRouteActionProvider.setRouteSelector(MediaRouteActionProvider.java:169)
at com.afollestad.impression.viewer.ViewerActivity.onCreateOptionsMenu(ViewerActivity.java:804)
When you state that a certain line of code is throwing an exception, it is useful to indicate which line of the code it is since we don't have your full source. Regarding your issue, in your onCreate), as it is stated in your post, you have MediaRouteSelector mMediaRouteSelector = .... Since we don't have your source code, I am going to assume that it is really as you have copied here. Since you also use mMediaRouteSelector in onCreateOptionsMenu(), it sounds like you have an instance variable mMediaRouteSelector which is shadowed in your onCreate(); in other words, the assignment made in onCreate() is local to that method and not global, hence it is practically null in onCreateOptionsMenu(). Change the assignment in onCreate() to
mMediaRouteSelector = new MediaRouteSelector.Builder()
.addControlCategory( CastMediaControlIntent.categoryForCast(getString(R.string.cast_sdk_id)))
.build();