RuntimeException: Unable to resume Activity due to NPE - android-fragments

When I resume to a fragment this exception occurs. This is the stack trace
Non-fatal Exception: java.lang.RuntimeException: Unable to resume activity {com.beco.ibeco/com.beco.ibeco.app.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3212)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3243)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1465)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5539)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
at com.beco.ibeco.app.store.StoreListFragment.onResume(StoreListFragment.java:141)
at android.support.v4.app.Fragment.performResume(Fragment.java:2235)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1346)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.FragmentManagerImpl.dispatchResume(FragmentManager.java:2898)
at android.support.v4.app.FragmentController.dispatchResume(FragmentController.java:223)
at android.support.v4.app.FragmentActivity.onResumeFragments(FragmentActivity.java:509)
at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:498)
at android.support.v7.app.AppCompatActivity.onPostResume(AppCompatActivity.java:172)
at android.app.Activity.performResume(Activity.java:6389)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3197)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3243)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1465)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5539)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
And this is the code
#Override
public void onResume() {
super.onResume();
Sample.getApp().setMallId(null);
Sample.getApp().setStoreId(null);
if(mMenu != null && mMenu.hasVisibleItems() && mMenu.getItem(0) != null)
mMenu.getItem(0).getIcon().setColorFilter(getResources().getColor(R.color.sample_black), PorterDuff.Mode.SRC_ATOP);
}
And I'm not able find where this NPE occurs. Any one please help me. Thanks in advance !

EDIT
To fix this I also had to check whether mMenu.getItem(0).getIcon() != null
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if(mMenu != null && mMenu.hasVisibleItems() && mMenu.getItem(0) != null && mMenu.getItem(0).getIcon() != null)
mMenu.getItem(0).getIcon().setColorFilter(ContextCompat.getColor(getContext(),R.color.beco_black), PorterDuff.Mode.SRC_ATOP);
}

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);
}
}

Unable to download file from firebase through android studio

i just want to download an image from Firebase storage,but i am having these issues.My google play service is up to date.I have an image "dog.jpg" in bucket and no other file.
Firebase bucket
My mainActivity code
public class MainActivity extends AppCompatActivity {
private StorageReference pathRef = FirebaseStorage.getInstance().getReference().child("dog.jpg");
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageView);
}
public void getImage(View v){
File localFile;
try {
localFile = File.createTempFile("images","jpg");
pathRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Local temp file has been created
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//handle error
Toast.makeText(MainActivity.this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_LONG).show();
}
});
}catch (IOException exception){
Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_SHORT).show();
}
}
}
Errors i am getting.
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11020000 but found 9683470
W/DynamiteModule: Local module descriptor class for com.google.android.gms.firebasestorage not found.
I/DynamiteModule: Considering local module com.google.android.gms.firebasestorage:0 and remote module com.google.android.gms.firebasestorage:0
E/NetworkRqFactoryProxy: NetworkRequestFactoryProxy failed with a RemoteException:
com.google.android.gms.dynamite.DynamiteModule$zzc: No acceptable module found. Local version is 0 and remote version is 0.
at com.google.android.gms.dynamite.DynamiteModule.zza(Unknown Source)
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/FileDownloadTask: Unable to create firebase storage network request.
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: null
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: null
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
whats wrong with my code...i even tried it on real device but still unable to download this file my storage rules are:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write:if true
}
}
}
Your Play services is not up to date as you suggest. This error message tells you what's going on:
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11020000 but found 9683470
The message suggests that you're using client library version 11.0.2, but Play services 9.6.83 is installed on the device. The version of Play has to be greater than or equal to the version of the client library in order for things to work.

e4 databinding converter exception not catch

I have created a custom converter to convert a String back into a Date.
public Object convert(Object fromObject){
if (fromObject != null && fromObject.toString().trim().length() == 0){
return null;
}
for (DateFormat f : formats){
try{
return f.parse(fromObject.toString());
}catch (ParseException e){
// Ignore
}
}
throw new RuntimeException(message);
}
Basically, if the string is not parsable a RuntimeException will be thrown.
I have added the converter to the update strategy in the data-dinding and it is being called.
The issue is when the exception is thrown. (For example when i start to type the date in the TextFiled). Instead of appearing the decorator field to indicated an error in the input, the exception is not catch.
The exception appears in the console log (The error in the logs is at the end of the question) as it seems that nobody is catching it.
What i am missing? The exception in the converter should be catch within the updateStrategy and display the error, shouldn't it?
!ENTRY org.eclipse.core.databinding 4 0 2017-08-18 15:16:27.816
!MESSAGE Invalid time Format
!STACK 0
java.lang.RuntimeException: Invalid time Format
at com.lsespace.earthcare.tds.gui.util.databinding.conversion.StringToJavaTimeTagConverter.convert(StringToJavaTimeTagConverter.java:21)
at org.eclipse.core.databinding.UpdateStrategy.convert(UpdateStrategy.java:715)
at org.eclipse.core.databinding.UpdateValueStrategy.convert(UpdateValueStrategy.java:1)
at org.eclipse.core.databinding.ValueBinding$3.run(ValueBinding.java:175)
at org.eclipse.core.databinding.observable.Realm$1.run(Realm.java:149)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.databinding.observable.Realm.safeRun(Realm.java:153)
at org.eclipse.core.databinding.observable.Realm.exec(Realm.java:171)
at org.eclipse.core.databinding.ValueBinding.doUpdate(ValueBinding.java:158)
at org.eclipse.core.databinding.ValueBinding.access$4(ValueBinding.java:147)
at org.eclipse.core.databinding.ValueBinding$1.handleValueChange(ValueBinding.java:46)
at org.eclipse.core.databinding.observable.value.ValueChangeEvent.dispatch(ValueChangeEvent.java:70)
at org.eclipse.core.databinding.observable.ChangeManager.fireEvent(ChangeManager.java:117)
at org.eclipse.core.databinding.observable.value.DecoratingObservableValue.fireValueChange(DecoratingObservableValue.java:61)
at org.eclipse.core.databinding.observable.value.DecoratingObservableValue.handleValueChange(DecoratingObservableValue.java:103)
at org.eclipse.core.databinding.observable.value.DecoratingObservableValue$1.handleValueChange(DecoratingObservableValue.java:76)
at org.eclipse.core.databinding.observable.value.ValueChangeEvent.dispatch(ValueChangeEvent.java:70)
at org.eclipse.core.databinding.observable.ChangeManager.fireEvent(ChangeManager.java:117)
at org.eclipse.core.databinding.observable.value.AbstractObservableValue.fireValueChange(AbstractObservableValue.java:82)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue.notifyIfChanged(SimplePropertyObservableValue.java:126)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue.access$3(SimplePropertyObservableValue.java:118)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue$1$1.run(SimplePropertyObservableValue.java:70)
at org.eclipse.core.databinding.observable.Realm$1.run(Realm.java:149)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.databinding.observable.Realm.safeRun(Realm.java:153)
at org.eclipse.core.databinding.observable.Realm.exec(Realm.java:171)
at org.eclipse.core.internal.databinding.property.value.SimplePropertyObservableValue$1.handleEvent(SimplePropertyObservableValue.java:66)
at org.eclipse.core.databinding.property.NativePropertyListener.fireChange(NativePropertyListener.java:69)
at org.eclipse.jface.internal.databinding.swt.WidgetListener.handleEvent(WidgetListener.java:56)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4410)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1084)
at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:3117)
at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:4939)
at org.eclipse.swt.widgets.Control.windowProc(Control.java:4794)
at org.eclipse.swt.widgets.Display.windowProc(Display.java:5115)
at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method)
at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:2446)
at org.eclipse.swt.widgets.Text.callWindowProc(Text.java:262)
at org.eclipse.swt.widgets.Control.windowProc(Control.java:4889)
at org.eclipse.swt.widgets.Text.windowProc(Text.java:2704)
at org.eclipse.swt.widgets.Display.windowProc(Display.java:5102)
at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method)
at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2552)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3814)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
at org.eclipse.jface.window.Window.open(Window.java:794)
at com.lsespace.earthcare.tds.gui.jface.actions.EditConfigAction.run(EditConfigAction.java:39)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
at org.eclipse.jface.action.ActionContributionItem.lambda$5(ActionContributionItem.java:436)
at org.eclipse.jface.action.ActionContributionItem$$Lambda$57/765702264.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4410)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4228)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3816)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
at org.eclipse.e4.ui.internal.workbench.swt.E4Application.start(E4Application.java:161)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
at org.eclipse.equinox.launcher.Main.main(Main.java:1492)
This is the implementation of the UpdateStrategy that I use so exceptions in the converter are treated like validation exceptions.
/**
* This implementation of UpdateValueStrategy does not catch the exceptions thrown by the converter,
* thus letting the normal mechanism of ValueBinding deal with the exception as it will do with a
* validation exception.
*
*/
public class AlternativeUpdateValueStrategy extends UpdateValueStrategy {
public AlternativeUpdateValueStrategy() {
this(UpdateValueStrategy.POLICY_UPDATE);
}
public AlternativeUpdateValueStrategy(int updateStrategy) {
super(updateStrategy);
}
#Override
public Object convert(Object value) {
if (converter != null) {
return converter.convert(value);
}
return value;
}
}

New Activity from FloatingActionButton

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>

updating array adapter onActivityResult after getting data from dialogfragment

My dilema is that i am coming from a dialogfragment to my weighInFragment with two pieces of information: a date and an int. I want to be able to use these two pieces of information and construct a newEntry which needs to be added to an existing Arrayadapter. The arraylist is displayed on the weighInFragment and i use the dialogfragment to capture information for new entries. However, when i try to add the new entry to the adapter i get a nullpointer exception which i believe is due to the adapter being null. So i am wondering how could i get this adapter and be able to add the new entry?
Here is y onActivityResult which is where i land after i hit "save" on my dialog:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case DATEPICKER_FRAGMENT:
if (resultCode == Activity.RESULT_OK) {
Bundle bundle=data.getExtras();
Date date = (Date) bundle.getSerializable("date");
int weight = (Integer) bundle.getSerializable("weight");
Log.d("NewEntry", "Date is: " + date + "Weight: " +weight );
WeighInAdapter adapter = (WeighInAdapter)getListAdapter();
WeighInEntry newEntry = new WeighInEntry();
newEntry.setDate(date);
newEntry.setWeight(weight);
adapter.add(newEntry);
adapter.notifyDataSetChanged();
} else if (resultCode == Activity.RESULT_CANCELED){
}
break;
}
}
This is where i get my data in the dialogadapter:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
// LayoutInflater inflater = getActivity().getLayoutInflater();
final View v = getActivity().getLayoutInflater()
.inflate(R.layout.weigh_in_dialog, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(v)
// Add action buttons
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatePicker datePicker = (DatePicker)v.findViewById(R.id.datePicker1);
EditText weightAmount = (EditText) v.findViewById(R.id.weight);
mDate = getDateFromDatePicket(datePicker);
mWeight = Integer.parseInt(weightAmount.getText().toString());
Intent i = new Intent();
Bundle extras=new Bundle();
extras.putSerializable("date", mDate); //putString("date",Month);
extras.putInt("weight",mWeight);
i.putExtras(extras);
getTargetFragment().onActivityResult(getTargetRequestCode(),Activity.RESULT_OK,i);
dismiss() ;
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
NewEntryDialogFragment.this.getDialog().cancel();
Log.d("CANCEL WAS PRESSED:", "!!!!!!!!!!!!");
}
});
return builder.create();
}
This is the logcat error:
11-17 17:42:51.050: D/NewEntry(2593): Date is: Tue Nov 17 17:42:51 EST 2015Weight: 200
11-17 17:42:51.060: D/AndroidRuntime(2593): Shutting down VM
11-17 17:42:51.060: W/dalvikvm(2593): threadid=1: thread exiting with uncaught exception (group=0xb1ae9b90)
11-17 17:42:51.070: E/AndroidRuntime(2593): FATAL EXCEPTION: main
11-17 17:42:51.070: E/AndroidRuntime(2593): Process: edu.bu.juanl.finalproject, PID: 2593
11-17 17:42:51.070: E/AndroidRuntime(2593): java.lang.NullPointerException
11-17 17:42:51.070: E/AndroidRuntime(2593): at edu.bu.juanl.finalproject.WeighInFragment.onActivityResult(WeighInFragment.java:141)
11-17 17:42:51.070: E/AndroidRuntime(2593): at edu.bu.juanl.finalproject.NewEntryDialogFragment$1.onClick(NewEntryDialogFragment.java:84)
11-17 17:42:51.070: E/AndroidRuntime(2593): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
11-17 17:42:51.070: E/AndroidRuntime(2593): at android.os.Handler.dispatchMessage(Handler.java:102)
11-17 17:42:51.070: E/AndroidRuntime(2593): at android.os.Looper.loop(Looper.java:137)
11-17 17:42:51.070: E/AndroidRuntime(2593): at android.app.ActivityThread.main(ActivityThread.java:4998)
11-17 17:42:51.070: E/AndroidRuntime(2593): at java.lang.reflect.Method.invokeNative(Native Method)
11-17 17:42:51.070: E/AndroidRuntime(2593): at java.lang.reflect.Method.invoke(Method.java:515)
11-17 17:42:51.070: E/AndroidRuntime(2593): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-17 17:42:51.070: E/AndroidRuntime(2593): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-17 17:42:51.070: E/AndroidRuntime(2593): at dalvik.system.NativeStart.main(Native Method)
11-17 17:42:53.440: I/Process(2593): Sending signal. PID: 2593 SIG: 9
ive tried multiple things and i cant figure it out!
The DialogPickerFragment inputs data from the user and this needs to be reflected in a different dialog fragment that contains a listview.
The data is being passed to the parent activity and it is trying to access an element belonging to the listview fragment. Herein lies the problem. The activity will not have access to the fragments list adapter.
What you should instead do is implement an interface between the activity and the listview fragment and pass in the data.Check out the android developer guide: http://developer.android.com/training/basics/fragments/communicating.html

Resources