DialogFragment isn't attached when I try to update it? - java

My attempt to simply/clearly explain a requirement to play music, show mp3 detail like time elapsed/remaining, and scrubbing with seek bar.
Activity hosts Fragment. Service has MediaPlayer.
Fragment simultaneously starts service and displays Dialog.
Dialog buttons control MediaPlayer. I can pause/play using av controls from the dialog.
NullPointerException occurs when I try to set dialog views with info. Seems the problem is that dialog doesn't attach quick enough for me to update with media player details and set seek bar progression.
I wasn't initially using a service but that approach didn't satisfy other requirements, like seamless audio on rotation and playing audio even if the dialog gets closed by the user.
Project source available on GitHub.
Update #1. Add stacktrace. Crash occurs at PreviewDialog.java:112. I commented this line in the linked repo with a note to uncomment in order to observe NPE.
0-07 14:35:09.475 12202-12202/com.es0329.workshop E/MediaPlayer-JNI: QCMediaPlayer mediaplayer NOT present
10-07 14:35:09.495 12202-12202/com.es0329.workshop E/MediaPlayer: Should have subtitle controller already set
10-07 14:35:09.500 12202-12202/com.es0329.workshop E/MediaPlayer: Should have subtitle controller already set
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: FATAL EXCEPTION: main
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: Process: com.es0329.workshop, PID: 12202
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at com.es0329.workshop.PreviewDialog.updateUi(PreviewDialog.java:112)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at com.es0329.workshop.PreviewDialog.onEvent(PreviewDialog.java:97)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at com.es0329.workshop.EventBus.publish(EventBus.java:40)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at com.es0329.workshop.MusicService$2.onPrepared(MusicService.java:50)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:2548)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5289)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
10-07 14:35:09.502 12202-12202/com.es0329.workshop E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Update #2. Post code snippet. When the MediaPlayer is ready, it notifies the dialog. If the dialog receives a message of "READY" it calls the #updateUi below. From what I can tell, the service begins and the mediaplayer data is ready/available BEFORE my dialog (which contains that timeRemaining textView) is attached.
private void updateUi(MediaPlayer player) {
int timeRemainingValue = player.getDuration();
timeRemaining.setText(String.valueOf(timeRemainingValue)); // NPE!
}

Add a try catch statement around the setting of the time remaining to handle to Null pointer exception.
General comment: I used created a new thread in my service which would update the UI information (i.e. duration text and SeekBar).

Related

Cannot capture image in the second time - Android

im using kevalpatel2106's android hidden camera library.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.exampleapp, PID: 10608
java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1865)
at android.hardware.Camera.takePicture(Camera.java:1806)
at com.androidhiddencamera.CameraPreview.takePictureInternal(CameraPreview.java:196)
at com.androidhiddencamera.HiddenCameraActivity.takePicture(HiddenCameraActivity.java:92)
at com.example.exampleapp.MainActivity.lambda$onCreate$3$MainActivity(MainActivity.java:152)
at com.example.exampleapp.MainActivity$$ExternalSyntheticLambda4.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7888)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
when the application instance taking picture the first time it works fine, but in the second time it throws me this error.
I'm using LGE LM-K520 device android 11.
this is the code:
findViewById(R.id.pic).setOnClickListener((a) -> takePicture());
this is my config:
mCameraConfig = new CameraConfig()
.getBuilder(MainActivity.this)
.setCameraFacing(CameraFacing.REAR_FACING_CAMERA)
.setCameraResolution(CameraResolution.HIGH_RESOLUTION)
.setImageFormat(CameraImageFormat.FORMAT_JPEG)
.setImageRotation(CameraRotation.ROTATION_90)
.build();
Thank You!!!

AndroidRuntime: FATAL EXCEPTION: main : application has stopped error

I get the error Fatal Exception main whenever I run application .
the app uses opencv 2.4.10 it has worked on one device and it fails on my device I couldn't figure out why this is happening.
I don't know which part is code is causing this error :
09-13 10:55:30.039 19555-19555/org.blatnik.eyemon E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.blatnik.eyemon, PID: 19555
java.lang.RuntimeException: Unable to start service org.blatnik.eyemon.MainService#66d5693 with Intent { flg=0x10000000 cmp=org.blatnik.eyemon/.MainService }: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4079)
at android.app.ActivityThread.access$2400(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1897)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:853)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:337)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at **org.opencv.android.BaseLoaderCallback.onPackageInstall(BaseLoaderCallback.java:110)
at org.opencv.android.AsyncServiceHelper.InstallService(AsyncServiceHelper.java:117)
at org.opencv.android.AsyncServiceHelper.initOpenCV(AsyncServiceHelper.java:33)
at org.opencv.android.OpenCVLoader.initAsync(OpenCVLoader.java:85)
at org.blatnik.eyemon.MainService.onStartCommand(MainService.java:140)**
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4062)
at android.app.ActivityThread.access$2400(ActivityThread.java:221) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1897) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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)
 
please any solution would be very thankful.
Apparently there is a task running which is using the context here with OpenCBLoader
(!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback))
The problem related with context i.e the context is not valid anymore
.Try passing getApplicationContext() instead of this
(!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, getApplicationContext(), mLoaderCallback))
Consider a case when AMK(android memory killer) kill your service due to memory shortage because service get to destroyed first before foreground activity and now your service is dead, plus the this context is not valid anymore hence Exception

Trying to get Android_ID bu the App crashes when i start it

That's the Code to get the AndroidID:
String userID = Settings.Secure.getString(getApplicationContext()
.getContentResolver(), Settings.Secure.ANDROID_ID);
When i start the Application i get the following logcat review:
04-28 01:30:02.012 9328-9328/com.hubermoritz.beercounter.beercounter02 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hubermoritz.beercounter.beercounter02, PID: 9328
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.hubermoritz.beercounter.beercounter02/com.hubermoritz.beercounter.beercounter02.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:114)
at com.hubermoritz.beercounter.beercounter02.MainActivity.<init>(MainActivity.java:48)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2296)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470) 
at android.app.ActivityThread.access$900(ActivityThread.java:174) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5593) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
at dalvik.system.NativeStart.main(Native Method) 
04
Tried with:
public String userID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
also, didn't work either. By the way I'm well aware off that it's not a perfect way to recognize users, because the number can change due to factory reset or changing phone and few other ways.
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:114)
at com.hubermoritz.beercounter.beercounter02.MainActivity.<init>(MainActivity.java:48)
You are attempting to call a method that you are inheriting from Activity from a field initializer. Do not do this. In general, do not call inherited methods on Activity until after super.onCreate() has been called in your onCreate() method. You are welcome to have a field, but do not initialize it until after super.onCreate().
You can't use getContentResolver until after the constructor is completed. Set this variable in your onCreate instead and you should be ok

Error, Null Pointer Exception for SharedPreferences

So I keep getting the same error no matter how many times I try to tweak my code here and there. I will be posting every little bit of code that has to do with the error.
I will not include unnecessary code so if my code doesn't look complete it's because I cut it out to make it easier for people to diagnose the issue!
First Class
I wrote !!! error !!! after the code that was said to have been the cause of the error according to my log.
SharedPreferences sf;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
sf = getSharedPreferences("MyData", MODE_PRIVATE);
checkCookie();
}
//function for making sure there's data
public void checkCookie() {
editor = sf.edit();
if (sf.getInt("cookies", -1) == -1) {
editor.putInt("cookies", 0);
}
}
//function for retrieving amount of cookies
public int getCookies()
{
editor = sf.edit(); !!! Error here !!!
int x = sf.getInt("cookies", 0);
return x;
}
//function for changing amount of cookies
public void changeCookies(int x)
{
editor = sf.edit();
editor.putInt("cookies", x);
}
Second Class
I put !!! error !!! at the second error given which basically is what calls the function with the error in it.
//MyActivity is the first class
MyActivity mCookie = new MyActivity();
//function for adding cookies
public void cookieCalc(){
if (Math.abs((5-(millis/1000))) <= 0.005)
mCookie.changeCookies(100 * CB); ... much more similar code
//an if statement within a function which just calls the function getcookies and cookiecalc
if (loop == 2){
cookieCalc();
myText.setText("= " + mCookie.getCookies()); !!! this calls the function which gives error !!!
}
The error is 100% because of SharedPreferences as it worked with normal variables, but I needed to save the variables and was told this is a very easy method to do so. If all of this is still not enough and I cannot explain it to you I will then paste my entire code on gitHub or another viewing platform.
Error Logs
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.MyActivity.changeCookies(MyActivity.java:74)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.cookieCalc(menu1_Fragment.java:75)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment$1.onClick(menu1_Fragment.java:148)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at android.view.View.performClick(View.java:5242)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at android.widget.TextView.performClick(TextView.java:10571)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21196)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:145)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6938)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
04-27 21:11:46.258 26975-26975/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
You should never create activity instance by yourself! Only system should do that.
If you create instance yourself, onCreate will never get called, as this instance won't go through standard activity lifecycle.
do not new instance by yourself. onCreate was br
Solved
SharedPreferences sf = this.getActivity().getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
because it was in a fragment class I had to add this.getActivity() and I also ended up adding Activity.MODE_PRIVATE. I probably was getting null pointer exception because it had no way to access my Activity class because fragments extend something else? Just a guess of mine, so far it is still not working how I want it to but I prevented crashes. edit it wasn't working because I didn't do editor.commit(); to save the changes.

Nested transactions are not allowed in Android studio

I am working on an android app and I am using realm DB, my app was worked properly, but suddenly if i want to write to DB the app stopped and give me this error.
Getting MAX_TEXTURE_SIZE from GradienCache
Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
---
FATAL EXCEPTION: main
java.lang.IllegalStateException: Nested transactions are not allowed. Use
commitTransaction() after each beginTransaction().
atio.realm.internal.ImplicitTransaction.promoteToWrite(ImplicitTransaction.java:)
at io.realm.Realm.beginTransaction(Realm.java:1454)
at.onClick(AddMedication.java:52)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Could not find class 'android.util.ArrayMap', referenced from method
com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources
I tried many available solutions but the problem have not fixed yet!
any help!
Probably you are calling beginTransaction() twice. Before the second call you must commit or rollback the first one.
beginTransaction(); // First call
try{
doSomeWorkOnDB();
commit();
} except (...){
rollback();
}
...
beginTransaction(); // Second call
try{
doOtherWorkOnDB();
commit();
} except (...){
rollback();
}
Hope it helps.

Categories