ANdroid lang runtime exception error, how to resolve it? - java

I am getting the following error in my android studio. Is there any way I can solve this issue. Its causing a lot of crashes in my app.
E/AndroidRuntime: FATAL EXCEPTION: Firebase-Messaging-Intent-Handle
Process: com.cnlcabs.cnldrivers, PID: 19224
java.lang.RuntimeException: Can't create handler inside thread Thread[Firebase-Messaging-Intent-Handle,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:227)
at android.os.Handler.<init>(Handler.java:129)
at com.cnlcabs.cnldrivers.data.MyFirebaseMessagingService.stopPlayer(MyFirebaseMessagingService.java:264)
at com.cnlcabs.cnldrivers.data.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:233)
at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(com.google.firebase:firebase-messaging##21.1.0:13)
at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(com.google.firebase:firebase-messaging##21.1.0:8)
at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(com.google.firebase:firebase-messaging##21.1.0:3)
at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(com.google.firebase:firebase-messaging##21.1.0:3)
at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(com.google.firebase:firebase-messaging##21.1.0:1)
at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(Unknown Source:6)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement##17.5.0:6)
at java.lang.Thread.run(Thread.java:923)
my code for myfirebasemessagingservice line 264 is
private void stopPlayer() {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (NotificationReceiverSoundPlay.mPlayer != null)
NotificationReceiverSoundPlay.mPlayer.stop();
}
}, 2000);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}

You need to run these lines in UI thread not in a separate thread. Like this answer.
new Handler().postDelayed(new Runnable() {
activity.runOnUiThread(new Runnable() {
public void run() {
if (NotificationReceiverSoundPlay.mPlayer != null)
NotificationReceiverSoundPlay.mPlayer.stop();
}
});
}, 2000);

Related

(AsyncTask) Open a dialog when catch (Jsoup)

I want the dialog to open when "AsyncTask" is "catch". I tried to call Dialogue into a “catch”. But the program is crashing. How do I open a dialog when there is a catch?
My code:
public class test extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = (Document) Jsoup.connect("(warn: here my web)").get();
test = doc.text();
} catch (Exception e)
//Here problem dialog open. App crash
OpenDialog();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
Toast.makeText(MainActivity.this, test, Toast.LENGTH_LONG).show();
}
}
logcat error (red):
2021-12-17 07:22:10.953 17530-17564/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process, PID: 17530
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:415)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #1,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:227)
at android.os.Handler.<init>(Handler.java:129)
at android.view.ViewRootImpl$ViewRootHandler.<init>(ViewRootImpl.java:5041)
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:5369)
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:763)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:399)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:111)
at android.app.Dialog.show(Dialog.java:342)
at Main.qaytaDialog(Main.java:130)
at Main.access$000(Main.java:24)
at Main$dooit.doInBackground(Main.java:95)
at Main$dooit.doInBackground(Main.java:83)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:923) 
A bit broad but here are some tips. Displaying dialogs is foreground thing (runs on main or UI thread) so it can not be done in background method of async task (it runs on background Thread).It is only allowed from methods such as onPostExecute(), onPublishProgress().
Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #1,5,main] that has not called Looper.prepare()
Please refer to this link for details
Here is a quick code snippet for your reference
public class MyAsync extends AsyncTask<Void, Void, Void> {
Boolean isCatched=false;
#Override
protected Void doInBackground(Void... voids) {
try {
if (!isCatched)
throw new Exception();
Log.i("Test", "doInBackground: ");
} catch (Exception e){
//Here problem dialog open. App crash
isCatched=true;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
if (isCatched)
OpenDialog();
Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_LONG).show();
}
}

android studion giving error on disableWebView() in android studio

I am trying to use BackgroundMode.disableWebViewOptimizations(); in my ionic app but when i launch the app in the android studio then i am getting this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.siloc.users, PID: 6275
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.View org.apache.cordova.CordovaWebViewEngine.getView()' on a null object reference
at de.appplant.cordova.plugin.background.BackgroundModeExt$1.lambda$run$0$BackgroundModeExt$1(BackgroundModeExt.java:169)
at de.appplant.cordova.plugin.background.-$$Lambda$BackgroundModeExt$1$ENae6xHnDD7pQOdOSwld6cT0QNo.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:230)
at android.app.ActivityThread.main(ActivityThread.java:7880)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:526)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
E/NetdClient: querySockNetidForUid nid:0, uid:10357, command.cmdId:11, id:0
This is the function in BackgroundModeExt.java file
private void disableWebViewOptimizations() {
Thread thread = new Thread(){
public void run() {
try {
Thread.sleep(1000);
getApp().runOnUiThread(() -> {
View view = webView.getEngine().getView();
try {
Class.forName("org.crosswalk.engine.XWalkCordovaView")
.getMethod("onShow")
.invoke(view);
} catch (Exception e){
view.dispatchWindowVisibilityChanged(View.VISIBLE);
}
});
} catch (InterruptedException e) {
// do nothing
}
}
};
thread.start();
}
iS there any way i can solve this problem?
Change line: View view = webView.getEngine().getView(); to View view = webView.getView();

AdMob Interstitial and error isLoaded must be called on the main UI thread

After user William suggest me to change my code for showing interstitial ad to this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//setDebugMode(true);
initialiseAccelerometer();
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getResources().getString(R.string.InterstitialAd_unit_id));
interstitial.setAdListener(new AdListener() {
public void onAdClosed() {
// Create another ad request.
final AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
interstitial.loadAd(adRequest);
}
});
// Create ad request.
final AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
interstitial.loadAd(adRequest);
}
and for showing ad this:
public synchronized void GameOver() {
if (lives_left > 0) {
//success! - game passed - save score
ScoreManager.save_localscore_simple(score_times[currentLevel], "" + currentLevel, false);
if (Level_Buttons.length >= currentLevel + 1)
ScoreManager.save_localscore_simple(unlocked, "unlock" + (currentLevel + 1));
if (sound_success != 0 && !sound_muted)
sp.play(sound_success, 1, 1, 0, 0, 1);
//open interstitial ad
if (interstitial.isLoaded()) {
interstitial.show();
}
} else {
//game not passed
if (sound_gameover != 0 && !sound_muted)
sp.play(sound_gameover, 1, 1, 0, 0, 1);
}
//open interstitial ad
if (interstitial.isLoaded()) {
interstitial.show();
}
StopMusic();
state = GAMEOVER;
}
On every gameover in game I get this error:
W/dalvikvm(20469): threadid=11: thread exiting with uncaught exception (group=0x4180bda0)
E/AndroidRuntime(20469): FATAL EXCEPTION: Thread-67543
E/AndroidRuntime(20469): Process: com.test.mygame, PID: 20469
E/AndroidRuntime(20469): java.lang.IllegalStateException: isLoaded must be called on the main UI thread.
E/AndroidRuntime(20469): at com.google.android.gms.common.internal.bh.b(SourceFile:251)
E/AndroidRuntime(20469): at com.google.android.gms.ads.internal.b.e(SourceFile:345)
E/AndroidRuntime(20469): at com.google.android.gms.ads.internal.client.m.onTransact(SourceFile:66)
E/AndroidRuntime(20469): at android.os.Binder.transact(Binder.java:361)
E/AndroidRuntime(20469): at com.google.android.gms.internal.ap$a$a.isReady(Unknown Source)
E/AndroidRuntime(20469): at com.google.android.gms.internal.au.isLoaded(Unknown Source)
E/AndroidRuntime(20469): at com.google.android.gms.ads.InterstitialAd.isLoaded(Unknown Source)
E/AndroidRuntime(20469): at com.test.mygame.MainGame.GameOver(MainGame.java:1128)
E/AndroidRuntime(20469): at com.test.mygame.MainGame.Step(MainGame.java:773)
E/AndroidRuntime(20469): at com.test.nudge.Screen.run(Screen.java:207)
E/AndroidRuntime(20469): at java.lang.Thread.run(Thread.java:841)
What is wrong here? Please explain me simple as possible because I`m newbie without any programming knowledge before :) Thanks!
This is maybe not the full answer, but It´s hard to say the right answer because it´s not clear from Your code above. You´ve not showed where You use GameOver(), but I think You called it in the wrong place, I think You call it in any background thread because inside GameOver You call interstitial.isLoaded() which causing Your problem. Like the stacktrace said, call it in the main ui thread. For exqample, call this inside Your GameOver():
runOnUiThread(new Runnable() {
#Override public void run() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
Possibly You have to call it with an activity reference, it depends from where Do You call GameOver():
mYourActivity.runOnUiThread(new Runnable() {
#Override public void run() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
});
Share my case and solution.
I did new thread and call isLoaded(). It got this same error.
So that I solve it by below code using Messager.
Hope this help.
Code as below.
Main thread:
public void onCreate() {
mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case ACTION_ADMOB_IS_LOADED:
MainActivity.logForDebug(TAG,"AdMob : Check for loaded");
if(mIAds.isLoaded()) {
MainActivity.logForDebug(TAG,"AdMob : Loaded ...... OK");
mIAds.show();
}
break;
}
}
};
}
Other thread
public void run(){
while(true){
Message message;
// ------ For AdMob ------
Message message = mHandler.obtainMessage(ACTION_ADMOB_IS_LOADED,null);
message.sendToTarget();
}
}

Android repeating async Task never calls onPostExecute

I have an async Task that repeats itself, until a statement is true. Therefore I use this code(simplified):
public class AnalyzingTask extends AsyncTask<String, JSONObject, Void>
{
private final ReentrantLock lock = new ReentrantLock();
private final Condition tryAgain = lock.newCondition();
private volatile boolean finished = false;
#Override
protected Void doInBackground(String... params)
{
try
{
lock.lockInterruptibly();
do {
...somecode...
publishProgress(result)
tryAgain.await();
}
while (!finished);
lock.unlock();
}
catch(Exception e){
publishProgress(null);
}
return null;
}
#Override
protected void onProgressUpdate(JSONObject... result)
{
..someCode...
if(state.equals("Available"))
{
terminateTask();
}
else
{
runAgain();
}
}
public void runAgain() {
// Call this to request data from the server again
tryAgain.signal();
}
public void terminateTask() {
// The task will only finish when we call this method
finished = true;
if(lock.isLocked())
{
lock.unlock();
}
}
#Override
protected void onCancelled() {
// Make sure we clean up if the task is killed
terminateTask();
}
#Override
protected void onPostExecute(Void result)
{
return;
}
}
I debugged this code, and terminateTask() gets called normal, after "state" has the right value.
Nevertheless, onPostExecuted never gets called. It wouldn't be a problem, but I cant start another Task, as long as this one is running.
Why is this Task not finishing as normal?
Stacktrace when adding signal() as asked in the comments:
8008-8008/com.michi.undroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.michi.undroid, PID: 8008
java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.signal(AbstractQueuedSynchronizer.java:1917)
at com.michi.undroid.AnalyzingTask.terminateTask(AnalyzingTask.java:166)
at com.michi.undroid.AnalyzingTask$1.run(AnalyzingTask.java:127)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

android.view.View.requestLayout(View.java:16431)

We're working in an android app with the 4 version and we need a mysql connection. We are doing this with a php file which returns the data base result. The following code are working because if we debug the project we can see the correct database result in the the System.out.println. line.
But, if we try to change one text in our app for the result of the database our app can’t run correctly and the error was in the t.setText(txt); line.
Can anybody help me with this problem? Do you have another idea to do the database connection or is it the correct way?
Thanks a lot.
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//FUNCIONA NO BORRAR
final httpHandler handler = new httpHandler();
Thread thread = new Thread()
{
#Override
public void run() {
try {
if(true) {
sleep(1000);
String txt = handler.post("http://www.golftipp.com/pruebas_android/app.php");
TextView t = (TextView) findViewById(R.id.textView2);
t.setText(txt);
System.out.println(txt);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
The error
05-30 02:42:50.331 1276-1291/es.softline.connexiodb.app E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-87
Process: es.softline.connexiodb.app, PID: 1276
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:824)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.requestLayout(View.java:16431)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
at android.view.View.requestLayout(View.java:16431)
at android.widget.TextView.checkForRelayout(TextView.java:6600)
at android.widget.TextView.setText(TextView.java:3813)
at android.widget.TextView.setText(TextView.java:3671)
at android.widget.TextView.setText(TextView.java:3646)
at es.softline.connexiodb.app.MainActivity$1.run(MainActivity.java:33)
Non-UI threads cannot access views, use runOnUiThread():
Thread thread = new Thread()
{
#Override
public void run() {
try {
if(true) {
sleep(1000);
String txt = handler.post("http://www.golftipp.com/pruebas_android/app.php");
TextView t = (TextView) findViewById(R.id.textView2);
runOnUiThread(new Runnable() {
#Override
public void run() {
// do UI updates here
t.setText(txt);
}
});
System.out.println(txt);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();

Categories