App crashing when hitting the send button? - android-fragments

I would like to post data from an edit text to a database/php script and have that data automatically displayed in a list view in the same fragment as the edit text but when clicking the send button my app crashes. Can anyone help?
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.truevision.cypher.library.JSONParser;
public class FragmentOne extends ListFragment {
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
ListView listView;
EditText editText;
Button sendBtn;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
// url to create new post
private static final String url_post_message = "http://example.com/myscript.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_one,container, false);
sendBtn = (Button) view.findViewById(R.id.sendBtn);
// button click event
sendBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// creating new post in background thread
new Post().execute("");
}
});
return view;
}
/**
* Background Async Task to Create new post
* */
class Post extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Posting..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating post
* */
protected String doInBackground(String... args) {
String messages = editText.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("messages", messages));
// getting JSON Object
// Note that create post url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_post_message,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created post
} else {
// failed to create post
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
PHP Code
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['messages'])) {
$messages = $_POST['messages'];
// include db connect class
require_once 'DB_Connect.php';
// connecting to db
$db = new DB_Connect();
// mysql inserting a new row
$result = mysql_query("INSERT INTO post(messages) VALUES('$messages')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Post successfully added.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Logcat:
07-26 17:37:53.489: D/OpenGLRenderer(28074): Flushing caches (mode 0)
07-26 17:38:01.046: I/Adreno200-EGLSUB(28589): <ConfigWindowMatch:2218>: Format RGBA_8888.
07-26 17:38:01.056: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5bd46000 size:13352960 offset:11816960 fd:55
07-26 17:38:01.056: D/OpenGLRenderer(28589): Enabling debug mode 0
07-26 17:38:01.256: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5cb02000 size:21319680 offset:19783680 fd:58
07-26 17:38:02.187: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5e057000 size:11816960 offset:10280960 fd:61
07-26 17:38:14.429: I/Adreno200-EGLSUB(28589): <ConfigWindowMatch:2218>: Format RGBA_8888.
07-26 17:38:14.429: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5ed9c000 size:16711680 offset:16404480 fd:64
07-26 17:38:14.459: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x5fd8c000 size:13762560 offset:13455360 fd:70
07-26 17:38:14.499: D/memalloc(28589): /dev/pmem: Mapped buffer base:0x60aac000 size:14069760 offset:13762560 fd:73
07-26 17:38:14.650: W/dalvikvm(28589): threadid=11: thread exiting with uncaught exception (group=0x40cc31f8)
07-26 17:38:15.010: E/AndroidRuntime(28589): FATAL EXCEPTION: AsyncTask #1
07-26 17:38:15.010: E/AndroidRuntime(28589): java.lang.RuntimeException: An error occured while executing doInBackground()
07-26 17:38:15.010: E/AndroidRuntime(28589): at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-26 17:38:15.010: E/AndroidRuntime(28589): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.lang.Thread.run(Thread.java:856)
07-26 17:38:15.010: E/AndroidRuntime(28589): Caused by: java.lang.NullPointerException
07-26 17:38:15.010: E/AndroidRuntime(28589): at com.truevision.cypher.FragmentOne$Post.doInBackground(FragmentOne.java:85)
07-26 17:38:15.010: E/AndroidRuntime(28589): at com.truevision.cypher.FragmentOne$Post.doInBackground(FragmentOne.java:1)
07-26 17:38:15.010: E/AndroidRuntime(28589): at android.os.AsyncTask$2.call(AsyncTask.java:264)
07-26 17:38:15.010: E/AndroidRuntime(28589): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-26 17:38:15.010: E/AndroidRuntime(28589): ... 5 more
07-26 17:38:15.310: D/OpenGLRenderer(28589): Flushing caches (mode 0)
07-26 17:38:15.310: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5bd46000 size:13352960 offset:11816960
07-26 17:38:15.310: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5cb02000 size:21319680 offset:19783680
07-26 17:38:15.310: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5e057000 size:11816960 offset:10280960
07-26 17:38:15.330: D/OpenGLRenderer(28589): Flushing caches (mode 0)
07-26 17:38:15.340: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5ed9c000 size:16711680 offset:16404480
07-26 17:38:15.340: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x5fd8c000 size:13762560 offset:13455360
07-26 17:38:15.340: D/memalloc(28589): /dev/pmem: Unmapping buffer base:0x60aac000 size:14069760 offset:13762560
07-26 17:38:15.841: D/OpenGLRenderer(28589): Flushing caches (mode 1)
07-26 17:38:16.591: E/WindowManager(28589): Activity com.truevision.cypher.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41689f50 that was originally added here
07-26 17:38:16.591: E/WindowManager(28589): android.view.WindowLeaked: Activity com.truevision.cypher.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#41689f50 that was originally added here
07-26 17:38:16.591: E/WindowManager(28589): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
07-26 17:38:16.591: E/WindowManager(28589): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
07-26 17:38:16.591: E/WindowManager(28589): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
07-26 17:38:16.591: E/WindowManager(28589): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
07-26 17:38:16.591: E/WindowManager(28589): at android.view.Window$LocalWindowManager.addView(Window.java:537)
07-26 17:38:16.591: E/WindowManager(28589): at android.app.Dialog.show(Dialog.java:278)
07-26 17:38:16.591: E/WindowManager(28589): at com.truevision.cypher.FragmentOne$Post.onPreExecute(FragmentOne.java:78)
07-26 17:38:16.591: E/WindowManager(28589): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
07-26 17:38:16.591: E/WindowManager(28589): at android.os.AsyncTask.execute(AsyncTask.java:511)
07-26 17:38:16.591: E/WindowManager(28589): at com.truevision.cypher.FragmentOne$1.onClick(FragmentOne.java:56)
07-26 17:38:16.591: E/WindowManager(28589): at android.view.View.performClick(View.java:3511)
07-26 17:38:16.591: E/WindowManager(28589): at android.view.View$PerformClick.run(View.java:14111)
07-26 17:38:16.591: E/WindowManager(28589): at android.os.Handler.handleCallback(Handler.java:605)
07-26 17:38:16.591: E/WindowManager(28589): at android.os.Handler.dispatchMessage(Handler.java:92)
07-26 17:38:16.591: E/WindowManager(28589): at android.os.Looper.loop(Looper.java:137)
07-26 17:38:16.591: E/WindowManager(28589): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-26 17:38:16.591: E/WindowManager(28589): at java.lang.reflect.Method.invokeNative(Native Method)
07-26 17:38:16.591: E/WindowManager(28589): at java.lang.reflect.Method.invoke(Method.java:511)
07-26 17:38:16.591: E/WindowManager(28589): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
07-26 17:38:16.591: E/WindowManager(28589): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
07-26 17:38:16.591: E/WindowManager(28589): at dalvik.system.NativeStart.main(Native Method)

The problem is NullPointerException, so something is not initialized. Looking the code seems
that inside doInBackground you use editText, but is not initialized. Use view.findViewById to initialize it first.

Related

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.

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.

wildflyserver giving error 404 when JavaServerFaces Authentication Filter code is compiled

I am trying to run a simple program in which user is restricted to open any xhtml page if he is no logged in. I am using wildfly 10 server.
When i try to run the code these two errors appear on my console
/* console view*/
06:59:35,161 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./JsfAuthentication.UndertowDeploymentInfoService: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./JsfAuthentication.UndertowDeploymentInfoService: java.lang.ClassNotFoundException: project.filter.loginFilter from [Module "deployment.JsfAuthentication.war:main" from Service Module Loader]
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:1079)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.start(UndertowDeploymentInfoService.java:284)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: project.filter.loginFilter from [Module "deployment.JsfAuthentication.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:801)
... 6 more
06:59:35,167 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 70) WFLYUT0021: Registered web context: /Ddt-0.0.1-SNAPSHOT
06:59:35,167 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 69) WFLYUT0021: Registered web context: /CssDataTable
06:59:35,172 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 67) WFLYUT0021: Registered web context: /PreventAccessInJsf
06:59:36,877 INFO [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 64) Initializing Mojarra 2.2.13.SP1 20160303-1204 for context '/UserAppForAddingUser'
06:59:36,892 INFO [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 66) Initializing Mojarra 2.2.13.SP1 20160303-1204 for context '/UserWebApplication-0.0.1-SNAPSHOT'
06:59:37,342 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 66) WFLYUT0021: Registered web context: /UserWebApplication-0.0.1-SNAPSHOT
06:59:37,345 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 64) WFLYUT0021: Registered web context: /UserAppForAddingUser
06:59:37,353 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "JsfAuthentication.war")]) - failure description: {
"WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host./JsfAuthentication.UndertowDeploymentInfoService" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./JsfAuthentication.UndertowDeploymentInfoService: java.lang.ClassNotFoundException: project.filter.loginFilter from [Module \"deployment.JsfAuthentication.war:main\" from Service Module Loader]
Caused by: java.lang.ClassNotFoundException: project.filter.loginFilter from [Module \"deployment.JsfAuthentication.war:main\" from Service Module Loader]"},
"WFLYCTL0412: Required services that are not installed:" => ["jboss.undertow.deployment.default-server.default-host./JsfAuthentication.UndertowDeploymentInfoService"],
"WFLYCTL0180: Services with missing/unavailable dependencies" => undefined
}
/* My web.xml file consist of details about url patterns of filter*/
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JsfAuthentication</display-name>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<filter>
<filter-name>LoggingFilter</filter-name>
<filter-class>project.filter.loginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
/loginFilter. java class code where filter is defined/
package project.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import project.web.bean;
public class loginFilter implements Filter{
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
bean session = (bean) req.getSession().getAttribute("bean");
String url = req.getRequestURI();
if(session == null || !session.isLogged) {
if(url.indexOf("forum.xhtml") >= 0 || url.indexOf("logout.xhtml") >= 0 ) {
resp.sendRedirect(req.getServletContext().getContextPath() + "/login.xhtml");
}else {
chain.doFilter(request,response);
}
}else {
if(url.indexOf("register.xhtml") >= 0 || url.indexOf("login.xhtml") >= 0 ) {
resp.sendRedirect(req.getServletContext().getContextPath() + "/forum.xhtml");
}else if(url.indexOf("logout.xhtml") >= 0) {
req.getSession().removeAttribute("bean");
resp.sendRedirect(req.getServletContext().getContextPath() + "/login.xhtml");
}else {
chain.doFilter(request,response);
}
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
Since Servlet 3.0 you can use #WebFilter annotation. Instead declaring filter in web.xml try to do it with annotation. Code below.
package project.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import project.web.bean;
import javax.servlet.annotation.WebFilter;
#WebFilter(filterName="loginFilter")
public class loginFilter implements Filter{
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
bean session = (bean) req.getSession().getAttribute("bean");
String url = req.getRequestURI();
if(session == null || !session.isLogged) {
if(url.indexOf("forum.xhtml") >= 0 || url.indexOf("logout.xhtml") >= 0 ) {
resp.sendRedirect(req.getServletContext().getContextPath() + "/login.xhtml");
}else {
chain.doFilter(request,response);
}
}else {
if(url.indexOf("register.xhtml") >= 0 || url.indexOf("login.xhtml") >= 0 ) {
resp.sendRedirect(req.getServletContext().getContextPath() + "/forum.xhtml");
}else if(url.indexOf("logout.xhtml") >= 0) {
req.getSession().removeAttribute("bean");
resp.sendRedirect(req.getServletContext().getContextPath() + "/login.xhtml");
}else {
chain.doFilter(request,response);
}
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}

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