updating array adapter onActivityResult after getting data from dialogfragment - android-fragments

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

Related

RequestDispatcher#forward() throws "Request method 'POST' not supported" when forwarding from #PostMapping to #GetMapping

request.getRequestDispatcher() is not calling the 'unauthorised' method in BaseController.java. Below is my code
UserController.java
#PostMapping(value = "{domain}/updateUserPoolVesselList")
#ResponseBody
public int updateUserPoolVesselList(
ServletResponse response, HttpSession session,
HttpServletRequest request) throws ServletException, IOException
{
if(true) {
request.getRequestDispatcher("/unauthorized").forward(request, response);
return 0;
}
BaseController.java
#GetMapping(value = "/unauthorized")
public String unauthorized()
{
LOG.info("BaseController - unauthorized() method");
return "unauthorized";
}
Error
2021-02-08 16:21:58 WARN PageNotFound:215 - Request method 'POST' not supported
Feb 08, 2021 4:22:01 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [springDispatcher] in context with path [/ScorpioManagementWebApp] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: getWriter() has already been called for this response] with root cause
java.lang.IllegalStateException: getWriter() has already been called for this response
at org.apache.catalina.connector.Response.getOutputStream(Response.java:550)
at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:210)
at javax.servlet.ServletResponseWrapper.getOutputStream(ServletResponseWrapper.java:105)
at javax.servlet.ServletResponseWrapper.getOutputStream(ServletResponseWrapper.java:105)
at org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper.getOutputStream(SaveContextOnUpdateOrErrorResponseWrapper.java:116)
at org.springframework.http.server.ServletServerHttpResponse.getBody(ServletServerHttpResponse.java:89)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:250)
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:231)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:174)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)

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

HttpSessionBindingListener.valueUnbound is not triggered on session timeout

We need to do some DB cleanup on session timeout, so implemented HttpSessionBindingListener and added an object to session on user login, we never remove it from session explicitly.
HttpSessionBindingListener.valueUnbound is triggered if we manually call session.invalidate but the problem is it doesn't get triggered on session timeout. I see an error in the console but not sure what the problem is.
Set the object into session on login and invalidate session on logout:
#Named("logincontroller")
#Stateful
public class LoginController implements ILoginController, Serializable {
#Inject
private Credentials credentials;
private ExternalContext ec = null;
private HttpServletRequest request =null;
private HttpServletResponse response=null;
private HttpSession session=null;
#PostConstruct
private void getLocalVariables() {
ec = FacesContext.getCurrentInstance().getExternalContext();
request= (HttpServletRequest)ec.getRequest();
session = request.getSession();
}
#Override
public boolean login() {
...
credentials.setUserName(getUserName().toUpperCase());
credentials.setUserPassword(getPassword());
// set the object into session on user login
session.setAttribute("credentials", credentials);
}
#Override
public void logout() {
...
try {
response.sendRedirect(path+"/faces/Exit.html");
// invalidate the session on logout
session.invalidate();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Credentials object implementing HttpSessionBindingListener
#Named("credentials")
#SessionScoped
public class Credentials implements ICredentials, Serializable, HttpSessionBindingListener {
...
#Override
public void valueBound(HttpSessionBindingEvent event) {
//do nothing
}
#Override
public void valueUnbound(HttpSessionBindingEvent event) {
try {
// run DB scripts to clean up
lockManager.releaseAllLocksForUser(getUserName().toUpperCase());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error Stacktrace:
15:13:03,252 INFO [org.jboss.as.repository] (ServerService Thread Pool -- 66) WFLYDR0009: Content C:<path>jbossstudio10\runtimes\jboss-eap\standalone\data\content\62\7ccffda3936daab4d3148eb2e51584f8372592 is obsolete and will be removed
15:13:03,299 INFO [org.jboss.as.repository] (ServerService Thread Pool -- 66) WFLYDR0002: Content removed from location C:\<path>\jbossstudio10\runtimes\jboss-eap\standalone\data\content\62\7ccffda3936daab4d3148eb2e51584f8372592\content
15:26:36,245 ERROR [stderr] (default task-22) Exception in thread "default task-22" org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.enterprise.context.SessionScoped
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.manager.BeanManagerImpl.getContext(BeanManagerImpl.java:689)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.getIfExists(ContextualInstanceStrategy.java:90)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.ContextualInstanceStrategy$CachingContextualInstanceStrategy.getIfExists(ContextualInstanceStrategy.java:165)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.ContextualInstance.getIfExists(ContextualInstance.java:63)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:83)
15:26:36,246 ERROR [stderr] (default task-22) at org.jboss.weld.bean.proxy.ProxyMethodHandler.getInstance(ProxyMethodHandler.java:125)
15:26:36,246 ERROR [stderr] (default task-22) at com.facility.security.Credentials$Proxy$_$$_WeldClientProxy.valueUnbound(Unknown Source) // unknown source??
15:26:36,246 ERROR [stderr] (default task-22) at io.undertow.servlet.core.SessionListenerBridge.attributeRemoved(SessionListenerBridge.java:132)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.server.session.SessionListeners.attributeRemoved(SessionListeners.java:81)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.server.session.InMemorySessionManager$SessionImpl.removeAttribute(InMemorySessionManager.java:500)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.servlet.core.SessionListenerBridge.sessionDestroyed(SessionListenerBridge.java:72)
15:26:36,247 ERROR [stderr] (default task-22) at io.undertow.server.session.SessionListeners.sessionDestroyed(SessionListeners.java:61)
15:26:36,248 ERROR [stderr] (default task-22) at io.undertow.server.session.InMemorySessionManager$SessionImpl.invalidate(InMemorySessionManager.java:528)
15:26:36,248 ERROR [stderr] (default task-22) at io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1.run(InMemorySessionManager.java:357)
15:26:36,248 ERROR [stderr] (default task-22) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
15:26:36,248 ERROR [stderr] (default task-22) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
15:26:36,248 ERROR [stderr] (default task-22) at java.lang.Thread.run(Thread.java:748)
Do I need to get a new session in valueUnbound to run my DB scripts? I thought that we still have session when valueUnbound is called. I did search stackoverflow but to no avail.
Any help is greatly appreciated.
Env: Windows 7 Enterrpise, JDK 1.8, JBoss EAP 7.0.0, CDI 1.2, Mojarra 2.2.12-jbossorg-2, deltaspike 1.8.1, Servlets 3.1, PrimeFaces 6.1, Oracle 11g
I've never really worked with HttpSessionBindingListener.valueUnbound, but it looks like the ordering of events is a bit jumbled between CDI and servlet behaviour. Specifically it looks like CDI is told to tear down session beans before HttpSessionBindingListener.valueUnbound is invoked. Hence the exception - when the method should be invoked, you no longer have session context active.
Possible solution is to twist your code around and not use HttpSessionBindingListener.valueUnbound and instead make Credentials.valueUnbound a #PreDestroy method. That way it should be invoked by CDI whenever that bean is going to be destroyed, no matter if the cause is session invalidation or timeout.

RuntimeException: Unable to resume Activity due to NPE

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

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>

Resources