New Activity from FloatingActionButton - button

i would launch an activity with a click in a floating action button, but when i click this, I get "Unfortunately, ... has stopped.". please help me!
questo è il codice del bottone di default, and this works
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
When change the code of a snackbar with the code of a new activity, this does not work
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent launchactivity=new Intent (getApplicationContext(),add.class);
startActivity(launchactivity);
}
});
This is my logcat
09-24 21:22:29.009 6353-6353/com.example.fra31.tradebooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fra31.tradebooks, PID: 6353
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fra31.tradebooks/com.example.fra31.tradebooks.add}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2356)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.fra31.tradebooks.add.onCreate(add.java:47)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5289) 
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:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115) 

you should try this.
Intent launchactivity = new Intent(MainActivity.this, add.class);
startActivity(launchactivity);

Intent launchactivity=new Intent (MainActivity.this,add.class);
startActivity(launchactivity);
and you should go to androidmanifest.xml and define your activity as this :
<activity android:name=".MainActivity">
</activity>

Related

Issue with catching RuntimeExceptions as NullPointerExceptions by an uncaught exception handler in Java FX applications

I read this post JavaFx 8 global exception handling and tried to handle uncaught exceptions in my application. It works fine as described in the post. But when I added a statement which caused a NullPointerException the UncaughtExceptionHandler did not catch this exception. Why ? Is there another thread handling this exception? Or do I have to set the DefaultUncaughtExceptionHandler? I read JavaDocs:
Uncaught exception handling is controlled first by the thread, then by the thread's ThreadGroup object and finally by the default uncaught exception handler. If the thread does not have an explicit uncaught exception handler set, and the thread's thread group (including parent thread groups) does not specialize its uncaughtException method, then the default handler's uncaughtException method will be invoked.
I have no idea how to get the solution which handles all uncaught exceptions. Can you help? Thanks for your support!!
This is the code:
package TestSimpleDialog;
public class Main extends Application {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private MyHandler myHandler = new MyHandler();
#Override
public void init() {
// Thread.currentThread is the FX-Launcher thread:
Thread.currentThread().setUncaughtExceptionHandler(myHandler);
System.out.println(Thread.currentThread().getUncaughtExceptionHandler());
try {
logger.addHandler(new FileHandler("java.myLOG"));
}
catch (IOException e) {
throw new IllegalStateException("IOException when adding File Handler");
}
}
#Override
public void start(Stage primaryStage) {
logger.info("Test Application started");
// Thread.currentThread() is the FX-Application thread:
Thread.currentThread().setUncaughtExceptionHandler(myHandler);
// If this thread has not had an uncaught exception handler explicitly set then this thread's ThreadGroup object
// is returned, unless this thread has terminated, in which case null is returned.
System.out.println(Thread.currentThread().getUncaughtExceptionHandler());
// try {
// URI uriTest = new URI(null);
// } catch (URISyntaxException e) {
// throw new IllegalStateException("URISyntaxException by testing");
// }
StackPane root = new StackPane();
Button button = new Button("Throw exception");
button.setOnAction(event -> {
throw new RuntimeException("** T E S T **") ;
});
root.getChildren().add(button);
Scene scene = new Scene(root, 150, 60);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
class MyHandler implements Thread.UncaughtExceptionHandler{
#Override
public void uncaughtException(Thread thread, Throwable throwable) {
System.out.println("MyHandler caught exception: "+throwable.getMessage());
logger.log(Level.SEVERE, "**TEST** threw an uncaught exception", throwable);
}
}
}
When I push the button, I have got this output on the console:
TestSimpleDialog.Main$MyHandler#49285759
Aug. 08, 2020 5:55:33 NACHM. TestSimpleDialog.Main start
INFORMATION: Test Application started
TestSimpleDialog.Main$MyHandler#49285759
MyHandler caught exception: ** T E S T **
Aug. 08, 2020 5:55:51 NACHM. TestSimpleDialog.Main$MyHandler uncaughtException
SCHWERWIEGEND: **TEST** threw an uncaught exception
java.lang.RuntimeException: ** T E S T **
at TestSimpleDialog.Main.lambda$start$0(Main.java:47)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher............
But when I activated this statement to get a NullPointerException
try {
URI uriTest = new URI(null);
} catch (URISyntaxException e) {
throw new IllegalStateException("URISyntaxException by testing");
}
I could see on the console that the exception was not caught because of missing the statement "MyHandler caught exception: " the class MyHandler prints on Sysout. Furthermore nothing is written on the logging file.
TestSimpleDialog.Main$MyHandler#22b2aa29
TestSimpleDialog.Main$MyHandler#22b2aa29
Aug. 08, 2020 6:16:51 NACHM. TestSimpleDialog.Main start
INFORMATION: Test Application started
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NullPointerException
at java.base/java.net.URI$Parser.parse(URI.java:3104)
at java.base/java.net.URI.<init>(URI.java:600)
at TestSimpleDialog.Main.start(Main.java:41)
at javafx.graphics/com.sun.javafx.application.............
Don't have an answer to how - just a tentative explanation to the why (looks like the first thought in my comments wasn't far off ;)
At its base is the fact that the Application is instantiated via reflection: whatever exceptions happen in init/start bubble up as errors in instantiation, namely as InvocationTargetException. And these are indeed handled by LauncherImpl.launchApplicationWithArgs by .. ex.printStackTrace
public static void launchApplicationWithArgs(final ModuleAccess mainModule,
final String mainClassName,
final String preloaderClassName, String[] args) {
// invoke, handle exception, line 472
...
} catch (InvocationTargetException ex) {
ex.printStackTrace();
abort(null, "Exception running application %1$s", tempAppClass.getName());
return;
}
Don't see any way to intercept that (which might be a bug .. or not).
Edit
To achieve logging (beyond printing to the error output) of errors coalesced into InvocationTargetException, an option might be to wrap the workload of the init/start method into a try .. catch ... block and manually invoke the handler, something like
#Override
public void init() throws Exception {
try {
// do stuff that might be throwing
throw new ArithmeticException("am I caught?");
} catch (Exception ex) {
// invoke the handler and re-throw
myHandler.uncaughtException(Thread.currentThread(), ex);
throw(ex);
}
}

Exception while registering to notification hub with userId in Xamarin Forms Android

I am working on a application in while i need to register the user to notification when he is logged in.When I call the registration while logging in I am getting an exception.Below is my code and exception.
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class PushNotificationServiceAndroid : FirebaseInstanceIdService, IPushNotificationService
{
const string TAG = "MyFirebaseIIDService";
NotificationHub hub;
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
NotificationHubConstants.Hub = new NotificationHub(AppConstants.NotificationHubName,
AppConstants.ListenConnectionString, this);
}
public void RegisterToNotificationHub()
{
try
{
LoggingManager.Enter("RegisterToNotificationHub");
var tags = new List<string>() { };
if (Helpers.ApplicationContext.CurrentLoggedInUserId != 0)
{
tags.Add(Helpers.ApplicationContext.CurrentLoggedInUserId.ToString());
}
//NotificationHubConstants.Hub.UnregisterAll(FirebaseInstanceId.Instance.Token);
var regID = NotificationHubConstants.Hub.Register(FirebaseInstanceId.Instance.Token, tags.ToArray());
LoggingManager.Exit("RegisterToNotificationHub");
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
public void UnRegisterFromNotificationHub()
{
try
{
LoggingManager.Enter("UnRegisterFromNotificationHub");
hub = new NotificationHub(AppConstants.NotificationHubName,
AppConstants.ListenConnectionString, this);
hub.UnregisterAll(FirebaseInstanceId.Instance.Token);
LoggingManager.Exit("UnRegisterFromNotificationHub");
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
}
when the app opens OnTokenRefresh() is called.Once the user logged into the app i am calling RegisterToNotificationHub() through dependency service.But while registering into notification hub i.e, at
var regID = NotificationHubConstants.Hub.Register(FirebaseInstanceId.Instance.Token, tags.ToArray());
i am getting the following exception.
Java.Lang.RuntimeException: Exception of type 'Java.Lang.RuntimeException' was thrown.
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <7f42d9b804da4869b3155f4a330679c7>:0
at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <2648c88210c943a888f6191db8d679d6>:0
at Android.Runtime.JNIEnv.CallObjectMethod (System.IntPtr jobject, System.IntPtr jmethod, Android.Runtime.JValue* parms) [0x0000e] in <871a122d80384347bfb5f33e1dee9682>:0
at WindowsAzure.Messaging.NotificationHub.Register (System.String pnsHandle, System.String[] tags) [0x00081] in <15e1a3139a484a5a85c0680e5d11bb86>:0
at BusinessViewChat.Droid.Dependencies.PushNotificationServiceAndroid.RegisterToNotificationHub () [0x00035] in E:\SourceTree\BusinessView\sourcecode\BusinessView\BusinessViewChat\BusinessViewChat.Android\Dependencies\PushNotificationServiceAndroid.cs:46
--- End of managed Java.Lang.RuntimeException stack trace ---
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at android.net.http.AndroidHttpClient.execute(AndroidHttpClient.java:252)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:219)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:178)
at com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:134)
at com.microsoft.windowsazure.messaging.NotificationHub.refreshRegistrationInformation(NotificationHub.java:296)
at com.microsoft.windowsazure.messaging.NotificationHub.registerInternal(NotificationHub.java:390)
at com.microsoft.windowsazure.messaging.NotificationHub.register(NotificationHub.java:143)
at mono.java.lang.RunnableImplementor.n_run(Native Method)
at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
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:5019)
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)
Can any one please help me in solving the issue.Thanks in advance.
It must be added to your manifest file under the application tag.
The next:
<uses-library android: name = "org.apache.http.legacy" android: required = "false" />
For more information visit the official documentation
I hope I helped you, Regards
I got this error message because of a space in tags. After removing the space it worked.
Example:
I was using:
tags.Add("mill_id: 1313");
After changing for:
tags.Add("mill_id:1313");
It worked.
Check your tags to see if any character is causing the error.

Calling Fragment from RecyclerView Adapter

I have a recyclerView that shows a list in cardView. This recyclerview is located in one fragment that shown in a viewPager tab. I want to go to new Fragment when thumbnail in cardview is clicked.
I implemented following onBindViewHolder in order to have this functionality:
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment productDetailFragment = new ProductDetailFragment();
(FragmentActivity)mContext).getSupportFragmentManager().beginTransaction()
.replace(R.id.grid_page_recycler_view, productDetailFragment).commit();
}
});
But after running, it returns:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.support.v7.widget.RecyclerView.findMinMaxChildLayoutPositions(RecyclerView.java:3757)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3494)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3019)
at android.view.View.measure(View.java:15819)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:666)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15819)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
at android.view.View.measure(View.java:15819)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:15819)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15819)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4890)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
at android.view.View.measure(View.java:15819)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1965)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1146)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1356)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1046)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4603)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
What's the reason? It's notable that if I want to call another activity, it is easy to implement.
Thanks.
And I must say that there are several similar questions here, but I could not use them.
Create one method for replacing fragment in your MAinActivity.
Take ViewPager in a Fragment and push it from MainActivity.
Now Call replace fragment method in your recyclerView Adapter.
public void replaceFragment(Fragment fragment) {
String backStateName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(backStateName) == null) {
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.frame_container, fragment, backStateName);
ft.addToBackStack(backStateName);
ft.commit();
}
}

GoogleApiClient.Builder.enableAutoManage in Fragment throws IllegalStateException: Recursive entry to executePendingTransactions

I have an AppCompatActivity that has 3 tabs using FragmentTabHost. One of the tabs uses LocationServices. I would like to have the smoothest possible user experience:
If the LocationService is off in the android system, and only if the user chooses the tab that needs the Location I would like to display the AlertDialog to let the user turn on the Location in the system settings.
I have a helper class that is supposed to do all this and it does work in 3 other places in my app. In those 3 places it works "directly" in the Activity, however in this place it needs to work "within" the Fragment of the tab.
The problem is that if I have the line:
builder.enableAutoManage(activity, 0, this);
then builder.build() throws an exception: IllegalStateException: Recursive entry to executePendingTransactions
Any idea how can I achieve my goal?
Here are some related code fragments:
public class CityPreferences extends AppCompatActivity {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("available_cities")
.setIndicator(getString(R.string.tab_all_cities))
, AvailableCityFragment.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("nearby_cities")
.setIndicator(getString(R.string.tab_nearby_cities))
, NearbyCityFragment.class, null);
}
}
In NearbyCityFragment I have this 1 line of code:
class NearbyCityFragment extends Fragment {
...
LocationServiceHelper.getInstance().startOrDisplayDialog(getActivity());
(I tried it in onAttach, onStart, onResume)
And here's my helper class' function:
public class LocationServiceHelper implements
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks {
public boolean startOrDisplayDialog(#NonNull final FragmentActivity activity) {
final boolean servicesConnected = GooglePlayServicesHelper.checkOrDisplayDialog(activity);
if (servicesConnected) {
final boolean isEnabled = isLocationEnabledInSystem(activity);
if (isEnabled) {
if (null == mGoogleApiClient) {
mContext = activity;
mActivity = activity;
final GoogleApiClient.Builder builder = new GoogleApiClient.Builder(mContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this);
// the next line seems to cause the problem:
builder.enableAutoManage(activity, 0, this);
mGoogleApiClient = builder
.build();
}
return start();
} else {
final Dialog dialog = getLocationDisabledDialog(activity);
GooglePlayServicesHelper.showDialog(dialog, activity);
}
}
return false;
}
And finally the exception:
06-10 10:23:04.831 26725-26725/com.fletech.android.redalert.debug E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.fletech.android.redalert.debug, PID: 26725
java.lang.IllegalStateException: Recursive entry to executePendingTransactions
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1473)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at com.google.android.gms.common.api.g.a(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.gI(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source)
at com.fletech.android.redalert.helper.LocationServiceHelper.startOrDisplayDialog(LocationServiceHelper.java:113)
at com.fletech.android.redalert.city.NearbyCityFragment.onAttach(NearbyCityFragment.java:44)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:907)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
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:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I believe you must use a unique clientId each time you enable auto manager. From the documentation:
clientId - A non-negative identifier for this client. At any given time, only one auto-managed client is allowed per id. To reuse an id you must first call stopAutoManage(FragmentActivity) on the previous client.

Webview crash after fragment tab change

I have a activity with 3 actionbar tabs. Each tab contains a webview which loads a URL at Fragment oncreate(). Everything is working fine but if i switch tabs quickly the onpagefinished appears after the tab change so when the calling fragment is gone, resulting in an NullPointerException. Is there a way to prevent this?
I tried in my fragment:
public void onDestroy() {
super.onDestroy();
try {
myWebView.stopLoading();
} catch (Exception e) {
}
try {
myWebView.clearView();
} catch (Exception e) {
}
and in my tab listener:
onTabSelected(Tab tab, FragmentTransaction ft) {
// StartActivity.mViewPager.setCurrentItem(tab.getPosition());
if (FinishedLoading == true){
ft.replace(R.id.fragment_container, fragment);
}
}
Both options don't prevent the APP to crash.
The error i recieve:
java.lang.NullPointerException
at com.***.Fragment1$MyWebViewClient.onPageFinished(Fragment1.java:233)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:389)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
I was facing this issue as well. If you haven't solved it, maybe you would like to try implementing onPause in your fragment like this:
#Override
public void onPause() {
if (webview.isShown() == false) {
webview.stopLoading();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
Where webview is your webview

Resources