Rectangle 27 26

Historical view of user application state management

Sessions in the traditional sense keep the user's state in the application inside the server. This may be the current page in a flow or what has been previously entered but not persisted to the main database yet.

The reason for this need was the lack of standards on the client side to effectively maintain the state without making client specific (i.e. browser specific) applications or plug-ins.

HTML5 and XML Header Request has over time standardized the notion of storing complex data including application state in standard way on the client (i.e. browser) side without resorting to going back and forth between the server.

REST services are generally called when there is a transaction that needs to be performed or if it needs to retrieve data.

REST services are meant to be called by the client-side application and not the end user directly.

For any request to the server, part of the request should contain the authorization token. How it is implemented is application specific, but in general is either a BASIC or CERTIFICATE form of authentication.

Form based authentication is not used by REST services. However, as noted above REST services are not meant to be called by the user, but by the application. The application needs to manage getting the authentication token. In my case I used cookies with JASPIC with OAuth 2.0 to connect to Google for authentication and simple HTTP Authentication for automated testing. I also used HTTP Header authentication via JASPIC for local testing as well (though the same approach can be performed in SiteMinder)

As per those examples, the authentication is managed on the client side (though SiteMinder or Google would store the authentication session on their end), there's nothing that can be done about that state, but it is not part of the REST service application.

Retrieval requests in REST are GET operations where a specific resource is requested and is cacheable. There is no need for server sessions because the request has everything it would need to retrieve the data: authentication and the URI.

As noted above, the client-side application itself calls the REST services along with the authentication that it manages on the client side as well.

What this means for REST services [if done correctly] is to take a single request to the REST server will contain everything that is needed for a single user operation that does everything that is needed in a single transaction, a Transaction Script is what the pattern is called.

This is done through a POST request usually, but others such as PUT can also be used.

A lot of contrived examples of REST (I myself did this) tried to follow as much of what has been defined in the HTTP protocol, after going through that I decided to be more pragmatic and left it to GET and POST only. The POST method does not even have to implement the POST-REDIRECT-GET pattern.

Regardless though, as I had noted above, the client-side application will be the one calling the service and it will only call the POST request with all the data when it needs to (not every time). This prevents constant requests to the server.

Though REST can be used for polling as well, I won't recommend it unless you have to use it because of browser compatibility. For that I would use WebSockets which I had designed an API contract for as well. Another alternative for older browsers is CometD.

If REST applications are supposed to be stateless, how do you manage s...

rest session-state
Rectangle 27 26

Historical view of user application state management

Sessions in the traditional sense keep the user's state in the application inside the server. This may be the current page in a flow or what has been previously entered but not persisted to the main database yet.

The reason for this need was the lack of standards on the client side to effectively maintain the state without making client specific (i.e. browser specific) applications or plug-ins.

HTML5 and XML Header Request has over time standardized the notion of storing complex data including application state in standard way on the client (i.e. browser) side without resorting to going back and forth between the server.

REST services are generally called when there is a transaction that needs to be performed or if it needs to retrieve data.

REST services are meant to be called by the client-side application and not the end user directly.

For any request to the server, part of the request should contain the authorization token. How it is implemented is application specific, but in general is either a BASIC or CERTIFICATE form of authentication.

Form based authentication is not used by REST services. However, as noted above REST services are not meant to be called by the user, but by the application. The application needs to manage getting the authentication token. In my case I used cookies with JASPIC with OAuth 2.0 to connect to Google for authentication and simple HTTP Authentication for automated testing. I also used HTTP Header authentication via JASPIC for local testing as well (though the same approach can be performed in SiteMinder)

As per those examples, the authentication is managed on the client side (though SiteMinder or Google would store the authentication session on their end), there's nothing that can be done about that state, but it is not part of the REST service application.

Retrieval requests in REST are GET operations where a specific resource is requested and is cacheable. There is no need for server sessions because the request has everything it would need to retrieve the data: authentication and the URI.

As noted above, the client-side application itself calls the REST services along with the authentication that it manages on the client side as well.

What this means for REST services [if done correctly] is to take a single request to the REST server will contain everything that is needed for a single user operation that does everything that is needed in a single transaction, a Transaction Script is what the pattern is called.

This is done through a POST request usually, but others such as PUT can also be used.

A lot of contrived examples of REST (I myself did this) tried to follow as much of what has been defined in the HTTP protocol, after going through that I decided to be more pragmatic and left it to GET and POST only. The POST method does not even have to implement the POST-REDIRECT-GET pattern.

Regardless though, as I had noted above, the client-side application will be the one calling the service and it will only call the POST request with all the data when it needs to (not every time). This prevents constant requests to the server.

Though REST can be used for polling as well, I won't recommend it unless you have to use it because of browser compatibility. For that I would use WebSockets which I had designed an API contract for as well. Another alternative for older browsers is CometD.

If REST applications are supposed to be stateless, how do you manage s...

rest session-state
Rectangle 27 38

Single page apps are those that live on a single HTML document. This means that if you want to display some different content to the user, depending on the state of the application, you will need to do some DOM manipulation (cutting out and replacing certain elements of the current document with different HTML) in order to update the 'view' that the user sees. Excuse me if this is obvious to you, please don't take offense. I figured I'd start from here. Hang with me and I'll explain how your routing situation is going to play out (more or less).

URLs are composed of a few different parts, each of which informs the browser of a particular bit of information that is required in order to download the resource that the user is attempting to access. Typically the resources that you are looking for are off on a server somewhere and the browser knows this because of pieces in the URL like 'protocol' ('http:') and 'host' ('www.mydomain.com'), so it goes off to that server to find what you're requesting. There are also 'query' parameters in URLs which provide some additional information to the server regarding a particular action, like the search terms of a search query. After the query parameters, comes the 'hash'. The hash is where the magic of single page apps happens... eh, well, kind of.....

First a bit about the hash. When you add a '#' to a URL, the browser then interprets the information that comes after it to be some location (element) within the currently displayed document. That means, if you have an element with an 'id' of 'main' and you add '#main' to the end of the URL, like so: 'http: //www.example.com#main', the browser will 'scroll' (typically 'jump') to the beginning of that element, so that the you can see it. Be aware, though, that if you type 'http://www.example.com/#main' (with the hash separated from the URL by a slash) then you will force a complete page reload and the browser will attempt to find a file by the name '#main' on the server (I bet it doesn't find it).

The takeaway here is that the browser will not attempt to navigate away from the current document if there is a hash in the URL

single-page apps don't want to navigate away from the page

Now, this whole thing about the hash isn't vital to single-page apps, as you could make one without dealing with it all. A bunch of click handlers and DOM manipulation is all you'd need really... But, that would mean that users will have no way of sharing links to particular views in your app. The URL would never change, and we would never be able to navigate to any particular view directly. We'd always be starting from the starting position of your app, which could easily be a very annoying situation.

If your single-page app is going to have different views, and you want users to be able to navigate directly to particular ones via bookmarks or links, then you will need to implement a form of routing on the front-end in addition to the routing that you'll need to implement on the backend (routing for data API, etc.), which means that you will need to make use of the hash.

I don't want to get into how different frameworks accomplish routing on the front-end, but it's basically a matter of updating the browser's address field when the user clicks a link, and watching the address bar to determine what the current URL is and loading the HTML that is associated with that URL into the DOM in the designated location in the document tree.

So, within a single-page app, you have one route on the server that deals with rendering the app HTML document (index.html), and you have routes that are responsible for dealing with the data of your app (creating new instances in the database, logging in and out, editing or destroying instances in the DB, and fetching data...) which are called via AJAX requests.

This is actually a fairly complicated situation in that HTML5 allows us to be able to forgo the hash (with the help of some link rewriting on the server) and also be able to use the 'back' and 'forward' buttons as if we've actually navigated away from the original document (which we haven't because we have only pointed the browser to the exact same URL, only with modified hash values, so no new page loads have occurred). Traditional site navigation and linking can be achieved by utilizing the browser's History API, which is available for IE beginning with version 10 (I believe), the rest of the big browser vendors were already on to it quite a bit earlier, so frameworks that leverage this technology will allow your users to navigate your app without the hash in the URL. Explaining this is a diversion and not necessary for understanding routing in single-page apps, but it is interesting and you'll have to learn it eventually anyway, probably..

AJAX should be used to request JSON from the server. AJAX requests will always hit your server because you don't include the hash symbol in AJAX requests (it would be ridiculous to do so because the hash is meant only for in-document browsing), so server-side routes must be responsible for exposing your data API (consider a RESTful one). While this is not their sole purpose in single-page apps, it is perhaps their most important one.

Soooo, to wrap it up, you will have two sets of routes. One on the client (as part of a client-side framework like AngularJS or EmberJS, the list goes on... I prefer Angular, but there is a fairly steep learning curve for that one.), and one on the server. When you think about 'server routes' think data API. When you think of 'page routing', remember that this all gets handled on the client, by the javascript that you delivered with the initial server response (this is the one and only necessary server-side route involved with rendering HTML to the browser, loading your 'index.html' and all of the necessary scripts and stylesheets, etc). You will use express.static middleware to serve static files, so you don't have to worry about assigning routes for that stuff.

EDIT A quick mention of AJAX implementation. On the server, you will have routes similar those that Alex has provided as examples and you will make calls to those URLs from the client using whatever XMLHttpRequest (XHR) object is exposed by your framework or library of choice. It is now considered more or less standard and best practice for frameworks/libraries to implement these requests as Promises http://wiki.commonjs.org/wiki/Promises/A. You should read a bit about it on your own, but I might be able to summarize it by saying that it is an asynchronous operation analogous to 'try, catch, throw' in synchronous operations. You will instantiate a promise object and through it you will attempt to load data from the server, for instance, via GET request. Make sure that you have assigned functions to handle requests made to the URL that you made the request to (server-side route)! This object that you instantiate and subsequently make the request to the server through, promises to return the result of the request to you once it comes back from the server (no matter whether it was successful or not) If it is successful, it will call a function that you have written and will supply it with the data from the server. If it fails, it will call a different function, also written by you, and will supply it with the error object (or 'reason' for failure), so you can handle the error appropriately.

whoa, thank you so much! the time you took to explain it soooo well. Thank you, it does help for sure. BTW, just yesterday I was watching a great presentation of promise/A+. Highly useful youtube.com/watch?v=hf1T_AONQJU

Nice, I'm glad it could help. This was my first time actually contributing to SO, which is probably a bit messed up considering how often I am here looking for answers... What framework are you using to build the front-end?

javascript - node.js and single page web application - Stack Overflow

javascript ajax json node.js express
Rectangle 27 38

Single page apps are those that live on a single HTML document. This means that if you want to display some different content to the user, depending on the state of the application, you will need to do some DOM manipulation (cutting out and replacing certain elements of the current document with different HTML) in order to update the 'view' that the user sees. Excuse me if this is obvious to you, please don't take offense. I figured I'd start from here. Hang with me and I'll explain how your routing situation is going to play out (more or less).

URLs are composed of a few different parts, each of which informs the browser of a particular bit of information that is required in order to download the resource that the user is attempting to access. Typically the resources that you are looking for are off on a server somewhere and the browser knows this because of pieces in the URL like 'protocol' ('http:') and 'host' ('www.mydomain.com'), so it goes off to that server to find what you're requesting. There are also 'query' parameters in URLs which provide some additional information to the server regarding a particular action, like the search terms of a search query. After the query parameters, comes the 'hash'. The hash is where the magic of single page apps happens... eh, well, kind of.....

First a bit about the hash. When you add a '#' to a URL, the browser then interprets the information that comes after it to be some location (element) within the currently displayed document. That means, if you have an element with an 'id' of 'main' and you add '#main' to the end of the URL, like so: 'http: //www.example.com#main', the browser will 'scroll' (typically 'jump') to the beginning of that element, so that the you can see it. Be aware, though, that if you type 'http://www.example.com/#main' (with the hash separated from the URL by a slash) then you will force a complete page reload and the browser will attempt to find a file by the name '#main' on the server (I bet it doesn't find it).

The takeaway here is that the browser will not attempt to navigate away from the current document if there is a hash in the URL

single-page apps don't want to navigate away from the page

Now, this whole thing about the hash isn't vital to single-page apps, as you could make one without dealing with it all. A bunch of click handlers and DOM manipulation is all you'd need really... But, that would mean that users will have no way of sharing links to particular views in your app. The URL would never change, and we would never be able to navigate to any particular view directly. We'd always be starting from the starting position of your app, which could easily be a very annoying situation.

If your single-page app is going to have different views, and you want users to be able to navigate directly to particular ones via bookmarks or links, then you will need to implement a form of routing on the front-end in addition to the routing that you'll need to implement on the backend (routing for data API, etc.), which means that you will need to make use of the hash.

I don't want to get into how different frameworks accomplish routing on the front-end, but it's basically a matter of updating the browser's address field when the user clicks a link, and watching the address bar to determine what the current URL is and loading the HTML that is associated with that URL into the DOM in the designated location in the document tree.

So, within a single-page app, you have one route on the server that deals with rendering the app HTML document (index.html), and you have routes that are responsible for dealing with the data of your app (creating new instances in the database, logging in and out, editing or destroying instances in the DB, and fetching data...) which are called via AJAX requests.

This is actually a fairly complicated situation in that HTML5 allows us to be able to forgo the hash (with the help of some link rewriting on the server) and also be able to use the 'back' and 'forward' buttons as if we've actually navigated away from the original document (which we haven't because we have only pointed the browser to the exact same URL, only with modified hash values, so no new page loads have occurred). Traditional site navigation and linking can be achieved by utilizing the browser's History API, which is available for IE beginning with version 10 (I believe), the rest of the big browser vendors were already on to it quite a bit earlier, so frameworks that leverage this technology will allow your users to navigate your app without the hash in the URL. Explaining this is a diversion and not necessary for understanding routing in single-page apps, but it is interesting and you'll have to learn it eventually anyway, probably..

AJAX should be used to request JSON from the server. AJAX requests will always hit your server because you don't include the hash symbol in AJAX requests (it would be ridiculous to do so because the hash is meant only for in-document browsing), so server-side routes must be responsible for exposing your data API (consider a RESTful one). While this is not their sole purpose in single-page apps, it is perhaps their most important one.

Soooo, to wrap it up, you will have two sets of routes. One on the client (as part of a client-side framework like AngularJS or EmberJS, the list goes on... I prefer Angular, but there is a fairly steep learning curve for that one.), and one on the server. When you think about 'server routes' think data API. When you think of 'page routing', remember that this all gets handled on the client, by the javascript that you delivered with the initial server response (this is the one and only necessary server-side route involved with rendering HTML to the browser, loading your 'index.html' and all of the necessary scripts and stylesheets, etc). You will use express.static middleware to serve static files, so you don't have to worry about assigning routes for that stuff.

EDIT A quick mention of AJAX implementation. On the server, you will have routes similar those that Alex has provided as examples and you will make calls to those URLs from the client using whatever XMLHttpRequest (XHR) object is exposed by your framework or library of choice. It is now considered more or less standard and best practice for frameworks/libraries to implement these requests as Promises http://wiki.commonjs.org/wiki/Promises/A. You should read a bit about it on your own, but I might be able to summarize it by saying that it is an asynchronous operation analogous to 'try, catch, throw' in synchronous operations. You will instantiate a promise object and through it you will attempt to load data from the server, for instance, via GET request. Make sure that you have assigned functions to handle requests made to the URL that you made the request to (server-side route)! This object that you instantiate and subsequently make the request to the server through, promises to return the result of the request to you once it comes back from the server (no matter whether it was successful or not) If it is successful, it will call a function that you have written and will supply it with the data from the server. If it fails, it will call a different function, also written by you, and will supply it with the error object (or 'reason' for failure), so you can handle the error appropriately.

whoa, thank you so much! the time you took to explain it soooo well. Thank you, it does help for sure. BTW, just yesterday I was watching a great presentation of promise/A+. Highly useful youtube.com/watch?v=hf1T_AONQJU

Nice, I'm glad it could help. This was my first time actually contributing to SO, which is probably a bit messed up considering how often I am here looking for answers... What framework are you using to build the front-end?

javascript - node.js and single page web application - Stack Overflow

javascript ajax json node.js express
Rectangle 27 142

MVP is not necessarily a scenario where the View is in charge (see Taligent's MVP for example). I find it unfortunate that people are still preaching this as a pattern (View in charge) as opposed to an anti-pattern as it contradicts "It's just a view" (Pragmatic Programmer). "It's just a view" states that the final view shown to the user is a secondary concern of the application. Microsoft's MVP pattern renders re-use of Views much more difficult and conveniently excuses Microsoft's designer from encouraging bad practice.

To be perfectly frank, I think the underlying concerns of MVC hold true for any MVP implementation and the differences are almost entirely semantic. As long as you are following separation of concerns between the view (that displays the data), the controller (that initialises and controls user interaction) and the model (the underlying data and/or services)) then you are acheiving the benefits of MVC. If you are acheiving the benefits then who really cares whether your pattern is MVC, MVP or Supervising Controller? The only real pattern remains as MVC, the rest are just differing flavours of it.

Consider this highly exciting article that comprehensively lists a number of these differing implementations. You may note that they're all basically doing the same thing but slightly differently.

I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not or to justify Microsofts Rapid Application Development tools. Neither of these reasons in my books justify its existence as a separate design pattern.

Thanks for the link to the Derek Greer article, that is an awesome read. +1 and a Nice Answer badge for that [after 1 1/2 years :-) ]

I've read several answers and blogs about the differences between MVC/MVP/MVVM/etc'. In effect, when you are down to business, it's all the same. It doesn't really matter whether you have an interface or not, and whether you are using a setter (or any other language feature). It appears that the difference between these patterns was born from the difference of various frameworks' implementations, rather than a matter of concept.

I wouldn't call MVP an anti-pattern, as later in the post "..the rest [including MVP] are just differing flavours of [MVC]..", which would imply that if MVP was an anti-pattern, so was MVC... it's just a flavor for a different framework's approach. (Now, some specific MVP implementations might be more or less desirable than some specific MVC implementations for different tasks...)

@Quibblsome: I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not [] Neither of these reasons in my books justify its existence as a separate design pattern. . It differs enough to make it distinct. In MVP, the view may be anything fulfilling a predefined interface (the View in MVP is a standalone component). In MVC, the Controller is made for a particular view (if relation's arities may make someone feel that's worth another term).

@Hibou57, there is nothing to stop MVC from referencing the view as an interface or creating a generic controller for several different views.

@quibblesome actually, there is. Controllers are, by definition, tightly bound to their corresponding views, for their job is to interpret human gestures (key presses, mouse updates, etc) into events for individual controls on a window. This is why you have a strict one controller, one view relationship. Controllers were never intended for form-wide use. For form-wide use, Application Model (aka Presentation Model) came into existence, which better suits that purpose. Since non-Smalltalk GUIs don't rely on MVC to implement controls, MVC makes relatively little sense in practice.

design patterns - What are MVP and MVC and what is the difference? - S...

design-patterns model-view-controller user-interface mvp glossary
Rectangle 27 141

MVP is not necessarily a scenario where the View is in charge (see Taligent's MVP for example). I find it unfortunate that people are still preaching this as a pattern (View in charge) as opposed to an anti-pattern as it contradicts "It's just a view" (Pragmatic Programmer). "It's just a view" states that the final view shown to the user is a secondary concern of the application. Microsoft's MVP pattern renders re-use of Views much more difficult and conveniently excuses Microsoft's designer from encouraging bad practice.

To be perfectly frank, I think the underlying concerns of MVC hold true for any MVP implementation and the differences are almost entirely semantic. As long as you are following separation of concerns between the view (that displays the data), the controller (that initialises and controls user interaction) and the model (the underlying data and/or services)) then you are acheiving the benefits of MVC. If you are acheiving the benefits then who really cares whether your pattern is MVC, MVP or Supervising Controller? The only real pattern remains as MVC, the rest are just differing flavours of it.

Consider this highly exciting article that comprehensively lists a number of these differing implementations. You may note that they're all basically doing the same thing but slightly differently.

I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not or to justify Microsofts Rapid Application Development tools. Neither of these reasons in my books justify its existence as a separate design pattern.

I've read several answers and blogs about the differences between MVC/MVP/MVVM/etc'. In effect, when you are down to business, it's all the same. It doesn't really matter whether you have an interface or not, and whether you are using a setter (or any other language feature). It appears that the difference between these patterns was born from the difference of various frameworks' implementations, rather than a matter of concept.

I wouldn't call MVP an anti-pattern, as later in the post "..the rest [including MVP] are just differing flavours of [MVC]..", which would imply that if MVP was an anti-pattern, so was MVC... it's just a flavor for a different framework's approach. (Now, some specific MVP implementations might be more or less desirable than some specific MVC implementations for different tasks...)

@Quibblsome: I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not [] Neither of these reasons in my books justify its existence as a separate design pattern. . It differs enough to make it distinct. In MVP, the view may be anything fulfilling a predefined interface (the View in MVP is a standalone component). In MVC, the Controller is made for a particular view (if relation's arities may make someone feel that's worth another term).

@Hibou57, there is nothing to stop MVC from referencing the view as an interface or creating a generic controller for several different views.

@quibblesome actually, there is. Controllers are, by definition, tightly bound to their corresponding views, for their job is to interpret human gestures (key presses, mouse updates, etc) into events for individual controls on a window. This is why you have a strict one controller, one view relationship. Controllers were never intended for form-wide use. For form-wide use, Application Model (aka Presentation Model) came into existence, which better suits that purpose. Since non-Smalltalk GUIs don't rely on MVC to implement controls, MVC makes relatively little sense in practice.

design patterns - What are MVP and MVC and what is the difference? - S...

design-patterns model-view-controller user-interface mvp glossary
Rectangle 27 140

MVP is not necessarily a scenario where the View is in charge (see Taligent's MVP for example). I find it unfortunate that people are still preaching this as a pattern (View in charge) as opposed to an anti-pattern as it contradicts "It's just a view" (Pragmatic Programmer). "It's just a view" states that the final view shown to the user is a secondary concern of the application. Microsoft's MVP pattern renders re-use of Views much more difficult and conveniently excuses Microsoft's designer from encouraging bad practice.

To be perfectly frank, I think the underlying concerns of MVC hold true for any MVP implementation and the differences are almost entirely semantic. As long as you are following separation of concerns between the view (that displays the data), the controller (that initialises and controls user interaction) and the model (the underlying data and/or services)) then you are acheiving the benefits of MVC. If you are acheiving the benefits then who really cares whether your pattern is MVC, MVP or Supervising Controller? The only real pattern remains as MVC, the rest are just differing flavours of it.

Consider this highly exciting article that comprehensively lists a number of these differing implementations. You may note that they're all basically doing the same thing but slightly differently.

I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not or to justify Microsofts Rapid Application Development tools. Neither of these reasons in my books justify its existence as a separate design pattern.

I've read several answers and blogs about the differences between MVC/MVP/MVVM/etc'. In effect, when you are down to business, it's all the same. It doesn't really matter whether you have an interface or not, and whether you are using a setter (or any other language feature). It appears that the difference between these patterns was born from the difference of various frameworks' implementations, rather than a matter of concept.

I wouldn't call MVP an anti-pattern, as later in the post "..the rest [including MVP] are just differing flavours of [MVC]..", which would imply that if MVP was an anti-pattern, so was MVC... it's just a flavor for a different framework's approach. (Now, some specific MVP implementations might be more or less desirable than some specific MVC implementations for different tasks...)

@Quibblsome: I personally think MVP has only been recently re-introduced as a catchy term to either reduce arguments between semantic bigots who argue whether something is truly MVC or not [] Neither of these reasons in my books justify its existence as a separate design pattern. . It differs enough to make it distinct. In MVP, the view may be anything fulfilling a predefined interface (the View in MVP is a standalone component). In MVC, the Controller is made for a particular view (if relation's arities may make someone feel that's worth another term).

@Hibou57, there is nothing to stop MVC from referencing the view as an interface or creating a generic controller for several different views.

@quibblesome actually, there is. Controllers are, by definition, tightly bound to their corresponding views, for their job is to interpret human gestures (key presses, mouse updates, etc) into events for individual controls on a window. This is why you have a strict one controller, one view relationship. Controllers were never intended for form-wide use. For form-wide use, Application Model (aka Presentation Model) came into existence, which better suits that purpose. Since non-Smalltalk GUIs don't rely on MVC to implement controls, MVC makes relatively little sense in practice.

design patterns - What are MVP and MVC and what is the difference? - S...

design-patterns model-view-controller user-interface mvp glossary
Rectangle 27 49

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo  {
    application.applicationIconBadgeNumber = 0;             
    //self.textView.text = [userInfo description];
    // We can determine whether an application is launched as a result of the user tapping the action
    // button or whether the notification was delivered to the already-running application by examining
    // the application state.

    if (application.applicationState == UIApplicationStateActive) {                
        // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.                
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Did receive a Remote Notification" message:[NSString stringWithFormat:@"Your App name received this notification while it was running:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];          
    }    
}

This works. A little more info about what it does; when the application is in the foreground, a native UI alert box appears with the notification text within it (the title is a slightly larger bolded text, and the message is smaller text under that. An 'OK' button to dismiss is at the bottom). The option applicationIconBadgeNumber being set to 0 is to hide the number that appears on top of the app icon in Springboard (for example signifying number of unread messages in a mail app). In this example, I don't know if that option is even needed.

iphone - Get push notification while App in foreground iOS - Stack Ove...

iphone ios objective-c push-notification
Rectangle 27 47

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo  {
    application.applicationIconBadgeNumber = 0;             
    //self.textView.text = [userInfo description];
    // We can determine whether an application is launched as a result of the user tapping the action
    // button or whether the notification was delivered to the already-running application by examining
    // the application state.

    if (application.applicationState == UIApplicationStateActive) {                
        // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.                
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Did receive a Remote Notification" message:[NSString stringWithFormat:@"Your App name received this notification while it was running:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];          
    }    
}

This works. A little more info about what it does; when the application is in the foreground, a native UI alert box appears with the notification text within it (the title is a slightly larger bolded text, and the message is smaller text under that. An 'OK' button to dismiss is at the bottom). The option applicationIconBadgeNumber being set to 0 is to hide the number that appears on top of the app icon in Springboard (for example signifying number of unread messages in a mail app). In this example, I don't know if that option is even needed.

iphone - Get push notification while App in foreground iOS - Stack Ove...

iphone ios objective-c push-notification
Rectangle 27 201

Like the docs say, think about it this way. If you were to do an application like a book reader, you will not want to load all the fragments into memory at once. You would like to load and destroy Fragments as the user reads. In this case you will use FragmentStatePagerAdapter. If you are just displaying 3 "tabs" that do not contain a lot of heavy data (like Bitmaps), then FragmentPagerAdapter might suit you well. Also, keep in mind that ViewPager by default will load 3 fragments into memory. The first Adapter you mention might destroy View hierarchy and re load it when needed, the second Adapter only saves the state of the Fragment and completely destroys it, if the user then comes back to that page, the state is retrieved.

I have multiple Buttons and TextViews in Fragment1 and ListView which generate items dynamically in Fragment2 and Fragment3. Do you think it is a good idea to use FragmentStatePagerAdapter and store all data in Activity, passing it to Fragments via Bundle?

@AlexMomotov Views in the Fragment's layout don't have anything to do with the choice of FragmentStatePagerAdapter. The question here is the amount of Fragments that will be paged through.

So basicaly there is nothing in favour of FragmentPagerAdapter to use it.

@Tomasz the advantage of FragmentPagerAdapter is that switching between fragments could be much faster, as the actual Fragment objects do not need to be rebuilt each time. On the other hand, this would end up using more memory holding the fragment objects in memory.

android - Difference between FragmentPagerAdapter and FragmentStatePag...

android android-fragments android-viewpager fragmentpageradapter fragmentstatepageradapter
Rectangle 27 5

viewWillUnload is usually not called except in the case of low memory.

- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

Or if you want to use code in your View Controller:

- (void)viewDidDisappear:(BOOL)animated
{
//Put code here
}

- (void)viewWillDisappear:(BOOL)animated
{
//Put code here
}

viewWill/DidDisappear will call when the app is closing. Not when Home Button pressed to minimize applications to control center.

iphone - Detect when home button is pressed iOS - Stack Overflow

iphone ios ipad ios5
Rectangle 27 5

View State: ViewState is used primarily by Server controls to retain state only on pages that post data back to themselves. The information is passed to the client and read back in a hidden variable. ViewState is an unnecessary overhead for pages that do not need it. As the ViewState grows larger, it affects the performance of garbage collection. Session State: A session is defined as a period of time that is shared between the web application and the user. Each user that is using the web application has their own session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table.

asp.net - What is the difference between SessionState and ViewState? -...

asp.net
Rectangle 27 5

View State: ViewState is used primarily by Server controls to retain state only on pages that post data back to themselves. The information is passed to the client and read back in a hidden variable. ViewState is an unnecessary overhead for pages that do not need it. As the ViewState grows larger, it affects the performance of garbage collection. Session State: A session is defined as a period of time that is shared between the web application and the user. Each user that is using the web application has their own session. Items/Objects can be placed into the Session which would only define these object for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table.

asp.net - What is the difference between SessionState and ViewState? -...

asp.net
Rectangle 27 6

Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

The Session caches every object that is in a persistent state (watched and checked for dirty state by Hibernate). If you keep it open for a long time or simply load too much data, it will grow endlessly until you get an OutOfMemoryException. One solution is to call clear() and evict() to manage the Session cache,keeping a Session open for the duration of a user session also means a higher probability of stale data.

I bet you haven't read through hibernate documentation itself, It has scenarios explaining them too :)

Suppose a user has to update a form, you get the details of user in from through UserObject, This user object is persistent with session. Now if user doesn't submit the form, your session is open until server session expires, how long will you wait? If you have used getCurrentSession, another form request comes while previous one is not submitted, you have got dirty data now!! What if your object is waiting for a data that is to come for a web-service and it taking long enough, will you still keep session open, object persistent with session?

Hibernate docs explain a motivation of a detached state, but they don't explain why do I need detached entities. As for me, I usually throw away all the detached entities. Furthermore, I very rarely use detach and clear methods. Instead, I let entities to become detached when session closes and I never reuse any of the session's entities then. I just can't understand motivation of reusing entities after they being detached.

Such methods become useful for the rare case where you are working with large volumes of objects and the persistence store might grow to such proportions that it starts to make a noticeable affect on performance. If you know that entities are no longer needed to be attached, you can then manually evict them and perhaps prevent having to go to the next step of complexity, which is to work in batches / multiple transactions.

java - Why need detached entities in JPA? - Stack Overflow

java hibernate jpa
Rectangle 27 20

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish(). The system may also destroy your activity if it's currently stopped and hasn't been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.

When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.

To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.

As the system begins to stop your activity, it calls onSaveInstanceState() (1) so you can specify additional state data you'd like to save in case the Activity instance must be recreated. If the activity is destroyed and the same instance must be recreated, the system passes the state data defined at (1) to both the onCreate() method (2) and the onRestoreInstanceState() method (3).

As your activity begins to stop, the system calls onSaveInstanceState() so your activity can save state information with a collection of key-value pairs. The default implementation of this method saves information about the state of the activity's view hierarchy, such as the text in an EditText widget or the scroll position of a ListView.

To save additional state information for your activity, you must implement onSaveInstanceState() and add key-value pairs to the Bundle object. For example:

static final String STATE_SCORE = "playerScore";
  static final String STATE_LEVEL = "playerLevel";

  @Override
  public void onSaveInstanceState(Bundle savedInstanceState) {
  // Save the user's current game state
  savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
  savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

  // Always call the superclass so it can save the view hierarchy state
  super.onSaveInstanceState(savedInstanceState);
}

Caution: Always call the superclass implementation of onSaveInstanceState() so the default implementation can save the state of the view hierarchy.

Activity

When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

For example, here's how you can restore some state data in onCreate():

@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState); // Always call the superclass first

 // Check whether we're recreating a previously destroyed instance
 if (savedInstanceState != null) {
    // Restore value of members from saved state
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
 } else {
    // Probably initialize members with default values for a new instance
 }

 }

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:

public void onRestoreInstanceState(Bundle savedInstanceState) {
  // Always call the superclass so it can restore the view hierarchy
  super.onRestoreInstanceState(savedInstanceState);

  // Restore state members from saved instance
  mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
  mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

Saving Android Activity state using Save Instance State - Stack Overfl...

android android-activity application-state
Rectangle 27 19

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish(). The system may also destroy your activity if it's currently stopped and hasn't been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.

When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.

To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.

As the system begins to stop your activity, it calls onSaveInstanceState() (1) so you can specify additional state data you'd like to save in case the Activity instance must be recreated. If the activity is destroyed and the same instance must be recreated, the system passes the state data defined at (1) to both the onCreate() method (2) and the onRestoreInstanceState() method (3).

As your activity begins to stop, the system calls onSaveInstanceState() so your activity can save state information with a collection of key-value pairs. The default implementation of this method saves information about the state of the activity's view hierarchy, such as the text in an EditText widget or the scroll position of a ListView.

To save additional state information for your activity, you must implement onSaveInstanceState() and add key-value pairs to the Bundle object. For example:

static final String STATE_SCORE = "playerScore";
  static final String STATE_LEVEL = "playerLevel";

  @Override
  public void onSaveInstanceState(Bundle savedInstanceState) {
  // Save the user's current game state
  savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
  savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

  // Always call the superclass so it can save the view hierarchy state
  super.onSaveInstanceState(savedInstanceState);
}

Caution: Always call the superclass implementation of onSaveInstanceState() so the default implementation can save the state of the view hierarchy.

Activity

When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

For example, here's how you can restore some state data in onCreate():

@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState); // Always call the superclass first

 // Check whether we're recreating a previously destroyed instance
 if (savedInstanceState != null) {
    // Restore value of members from saved state
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
 } else {
    // Probably initialize members with default values for a new instance
 }

 }

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:

public void onRestoreInstanceState(Bundle savedInstanceState) {
  // Always call the superclass so it can restore the view hierarchy
  super.onRestoreInstanceState(savedInstanceState);

  // Restore state members from saved instance
  mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
  mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

Saving Android Activity state using Save Instance State - Stack Overfl...

android android-activity application-state
Rectangle 27 2

Logout and Login

public class MainActivity extends FragmentActivity {
    String TAG="MainActivity";
    private static final String PERMISSION = "publish_actions";

    //private static final String PERMISSION = "email";

    private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";

    private Button postStatusUpdateButton;
    private LoginButton loginButton;
    private ProfilePictureView profilePictureView;
    private TextView greeting;
    private PendingAction pendingAction = PendingAction.NONE;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;

    Button LogoutButton,Pro;

/*  private static final List<String> PERMISSION = Arrays.asList(
            "email","publish_actions");*/


    private enum PendingAction
    {
        NONE, POST_STATUS_UPDATE
    }

    private UiLifecycleHelper uiHelper;

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) 
        {
            onSessionStateChange(session, state, exception);
        }
    };

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall,
                Exception error, Bundle data) {
            Log.d(TAG, String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall,
                Bundle data) {
            Log.d(TAG, "Success!");
        }
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);
        // Can we present the share dialog for regular links?
        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        setContentView(R.layout.activity_main);



        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() 
        {
                    @Override
                    public void onUserInfoFetched(GraphUser user) 
                    {
                        MainActivity.this.user = user;
                        updateUI();
                        // It's possible that we were waiting for this.user to
                        // be populated in order to post a status update.
                        handlePendingAction();


                    }
                });

        profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
        greeting = (TextView) findViewById(R.id.greeting);

        postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
        postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
            }
        });

          LogoutButton=(Button)findViewById(R.id.LogoutButton);
          LogoutButton.setOnClickListener(new View.OnClickListener() 
          {

            @Override
            public void onClick(View v)
            {

                //callFacebookLogout(session);
                Logout();

            }
        });

    }

    //override lifecycle methods so that UiLifecycleHelper know about state of the activity
    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();
        updateUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    private void onSessionStateChange(Session session, SessionState state,Exception exception) 
    {
        if (state.isOpened()) {
            Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();

            getUserData(session,state);



        } else if (state.isClosed()) {
            Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
        }
        if (pendingAction != PendingAction.NONE
                && (exception instanceof FacebookOperationCanceledException 
                || exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(MainActivity.this)//if permission is not granted
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null).show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() 
    {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        postStatusUpdateButton.setEnabled(enableButtons
                || canPresentShareDialog);

        if (enableButtons && user != null) 
        {
            profilePictureView.setProfileId(user.getId());
            greeting.setText(getString(R.string.hello_user, user.getFirstName()));



        } else {
            profilePictureView.setProfileId(null);
            greeting.setText(null);
        }


    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
        case POST_STATUS_UPDATE:
            postStatusUpdate();
            break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result,
            FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post,
                    message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null).show();
    }

    // create sample post to update on facebook
    private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
        return new FacebookDialog.ShareDialogBuilder(this)
                .setName("Hello Facebook")
                .setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
                .setLink("http://androidsrc.net/");
    }

    private void postStatusUpdate() {
        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        } else if (user != null && hasPublishPermission()) {
            final String message = getString(R.string.status_update,
                    user.getFirstName(), (new Date().toString()));
            Request request = Request.newStatusUpdateRequest(
                    Session.getActiveSession(), message, place, tags,
                    new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(message,
                                    response.getGraphObject(),
                                    response.getError());
                        }
                    });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    //check if app has permission to publish on facebook
    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when
                // we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                        this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }

    public void Logout()
    {
        if (Session.getActiveSession() != null) 
        {
            Session.getActiveSession().closeAndClearTokenInformation();
            Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
        }

        Session.setActiveSession(null);
    }




    private void getUserData(Session session, SessionState state)
    {
        if (state.isOpened())
        {
            Request.newMeRequest(session, new Request.GraphUserCallback()
            {
                @Override
                public void onCompleted(GraphUser user, Response response)
                {
                    if (response != null)
                    {
                        try
                        {
                            String name = user.getName();
                            // If you asked for email permission
                            String email = (String) user.getProperty("email");
                           // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                            Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            //Log.d(LOG_TAG, "Exception e");
                        }

                    }
                }
            }).executeAsync();
        }
    }
public void Logout()
        {
            if (Session.getActiveSession() != null) 
            {
                Session.getActiveSession().closeAndClearTokenInformation();
                Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
            }

            Session.setActiveSession(null);
        }

Facebook SDK 3.0 Logout Not Working in android Application from any ot...

android facebook facebook-login facebook-android-sdk
Rectangle 27 2

Update: current strategy is to move WebView instance to Application class instead of retained fragment when it's detached and reattach on resume as Josh does. To prevent Application from closing, you should use foreground service, if you want to retain state when user switches between applications.

class MyFragment extends Fragment{  

    public MyFragment(){  setRetainInstance(true); }

    private WebView webView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View v = ....
       LinearLayout ll = (LinearLayout)v.findViewById(...);
       if (webView == null) {
            webView = new WebView(getActivity().getApplicationContext()); 
       }
       ll.removeAllViews();
       ll.addView(webView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

       return v;
    }

    @Override
    public void onDestroyView() {
        if (getRetainInstance() && webView.getParent() instanceof ViewGroup) {
           ((ViewGroup) webView.getParent()).removeView(webView);
        }
        super.onDestroyView();
    } 
}

Please note that this method no longer stores the display data for this WebView. The previous behavior could potentially leak files if restoreState(Bundle) was never called.

Note that while setRetainInstance does retain the Fragment the view (and hence the WebView) still gets destroyed.

@Fred Can you provide a source for that statement? I have tested this in a small app which has a fragment with setRetainInstance(true) that displays a youtube page and if I change the orientation, the view seems to be retained as the video is not interrupted. Doesn't seem like the webview is getting destroyed.

@Rai It's was just a misreading, I have edited a bit the answer since then(it still needs some wording fixes). If you are interested in current state of affairs - this method works. However the problem is that android kills application when it's low on memory. I have an important input form where user has to read a message in another application, so I had to use foreground service with notification to prevent process from being killed. Yet android still destroys activity and hence the retained frame. But the instance of Application class is preserved - so I move WebView to Application now.

I also use MutableContextWrapper as base of the WebView, I switch contexts to activities on attach and detach. Another big problem that Chromium build in zoom controls save reference to old activity, so no zoom in solution with WebView attached to Application instead of Activity. TL;DR; if your form is not that important, and you may live with fact that after app switching your process can be killed and webview not restored go with retained frame solution. P.S. also I think that Google employees are far, far from real life problems with all their widgets-gadgets..

Android WebView: handling orientation changes - Stack Overflow

android webview orientation
Rectangle 27 62

I came up with a rock-solid solution for these issues that conforms with the 'Android Way' of things. I have all my long-running operations using the IntentService pattern. That is my activities broadcast intents, the IntentService does the work, saves the data in the DB and then broadcasts STICKY intents. The sticky part is important, such that even if the Activity was paused during during the time after the user initiated the work and misses the real time broadcast from the ItentService we can still respond and pick up the data from the calling Activity.ProgressDialogs can work into this pattern quite nicely with onSaveInstanceSate(). Basically, you need to save a flag that you have a progress dialog running in the saved instance bundle. DO NOT save the progress dialog object because this will leak the entire Activity. To have a persistent handle to the progress dialog, I store it as a Weak-reference in the application object. On orientation change or any thing else that causes the Activity to pause (phone call, user hits home etc) and then resume, I dismiss the old dialog and recreate a new dialog in the newly created Activity. For indefinite progress dialogs this is easy. For progress bar style, you have to put the last known progress in the bundle and whatever information you're using locally in the activity to keep track of the progress. On restore the progress, you'll use this information to re-spawn the progress bar in the same state as before and then update based on the current state of things. So to summarize, putting long-running tasks into an IntentService coupled with juidcious use of onSaveInstanceState() allows you to efficiently keep track of dialogs and restore then across the Activity life-cycle events. Relevant bits of Activity code are below. You'll also need logic in your BroadcastReceiver to handle Sticky intents appropriately, but that is beyond the scope of this.

public void doSignIn(View view) {
        waiting=true;
        AppClass app=(AppClass) getApplication();
        String logingon=getString(R.string.signon);
        app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
..}


@Override
    protected void onSaveInstanceState(Bundle saveState) {
        super.onSaveInstanceState(saveState);
        saveState.putBoolean("waiting",waiting);
    }

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if(savedInstanceState!=null) {
                restoreProgress(savedInstanceState);

            }
...}


private void restoreProgress(Bundle savedInstanceState) {
        waiting=savedInstanceState.getBoolean("waiting");
        if (waiting) {
            AppClass app=(AppClass) getApplication();
            ProgressDialog refresher=(ProgressDialog) app.Dialog.get();
            refresher.dismiss();
            String logingon=getString(R.string.signon);
            app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));



        }

    }

seems a nice solution

"I have all my long-running operations using the IntentService pattern." This is not a perfect solution because it is like to shoot out of cannon into sparrows and a lot boilerplate code, for more you can watch youtube.com/watch?v=NJsq0TU0qeg

android - How to handle screen orientation change when progress dialog...

android android-activity android-dialog
Rectangle 27 62

I came up with a rock-solid solution for these issues that conforms with the 'Android Way' of things. I have all my long-running operations using the IntentService pattern. That is my activities broadcast intents, the IntentService does the work, saves the data in the DB and then broadcasts STICKY intents. The sticky part is important, such that even if the Activity was paused during during the time after the user initiated the work and misses the real time broadcast from the ItentService we can still respond and pick up the data from the calling Activity.ProgressDialogs can work into this pattern quite nicely with onSaveInstanceSate(). Basically, you need to save a flag that you have a progress dialog running in the saved instance bundle. DO NOT save the progress dialog object because this will leak the entire Activity. To have a persistent handle to the progress dialog, I store it as a Weak-reference in the application object. On orientation change or any thing else that causes the Activity to pause (phone call, user hits home etc) and then resume, I dismiss the old dialog and recreate a new dialog in the newly created Activity. For indefinite progress dialogs this is easy. For progress bar style, you have to put the last known progress in the bundle and whatever information you're using locally in the activity to keep track of the progress. On restore the progress, you'll use this information to re-spawn the progress bar in the same state as before and then update based on the current state of things. So to summarize, putting long-running tasks into an IntentService coupled with juidcious use of onSaveInstanceState() allows you to efficiently keep track of dialogs and restore then across the Activity life-cycle events. Relevant bits of Activity code are below. You'll also need logic in your BroadcastReceiver to handle Sticky intents appropriately, but that is beyond the scope of this.

public void doSignIn(View view) {
        waiting=true;
        AppClass app=(AppClass) getApplication();
        String logingon=getString(R.string.signon);
        app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
..}


@Override
    protected void onSaveInstanceState(Bundle saveState) {
        super.onSaveInstanceState(saveState);
        saveState.putBoolean("waiting",waiting);
    }

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if(savedInstanceState!=null) {
                restoreProgress(savedInstanceState);

            }
...}


private void restoreProgress(Bundle savedInstanceState) {
        waiting=savedInstanceState.getBoolean("waiting");
        if (waiting) {
            AppClass app=(AppClass) getApplication();
            ProgressDialog refresher=(ProgressDialog) app.Dialog.get();
            refresher.dismiss();
            String logingon=getString(R.string.signon);
            app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));



        }

    }

seems a nice solution

"I have all my long-running operations using the IntentService pattern." This is not a perfect solution because it is like to shoot out of cannon into sparrows and a lot boilerplate code, for more you can watch youtube.com/watch?v=NJsq0TU0qeg

android - How to handle screen orientation change when progress dialog...

android android-activity android-dialog