问:
How to solve Stripe elements for react causing memory leak on redirect
I have a component where I'm giving my users an option to subscribe to remove ads from the app. I integrated Stripe perfectly until I came to the redirect portion of the app. Since I don't want to have people create multiple subscriptions if my users have an active subscription (which I'm getting from firebase db), then I want to redirect my users to another page. This is causing me to see a warning about memory leaks once the redirect takes place. This doesn't happen anymore after trying to navigate back to the subscription component. Here's my component stripped away with most code that doesn't cause the error to show. I figured it was stripe elements because If I remove the call to that component, then all works great, and no memory leaks. Has anyone ever experienced this issue and have a fix?

I feel like it has to do with the way I'm setting the show form using the React.useEffect hook. Any help is truly appreciated!

```<code>import React, { Component } from 'react';
import { compose } from 'recompose';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { Redirect } from 'react-router-dom';
import StripeForm from '../components/StripeForm';
import Grid from '@material-ui/core/Grid';

import {
    AuthUserContext,
    withAuthorization,
    withEmailVerification,
} from '../components/Session';
import { withFirebase } from '../components/Firebase';
const stripePromise = loadStripe('stripe-key-here');

const AccountPage = (props) => {
    const show = props.firebase.userData.stripe.subscriptions.subscription.plan.active
    const [showForm, setShowForm] = React.useState(show)

    React.useEffect(() => {
        if (show !== showForm) {
            setShowForm(show);
        }
    }, [show, showForm])

    return (

        <AuthUserContext.Consumer>
            {authUser => {
                return (
                    <>
                        {showForm ? <Redirect to="/thank-you" /> : null}
                        <Grid container spacing={3} style={{ background: '#fff', maxWidth: '94%', margin: '20px auto', borderRadius: 7 }}>
                            <Grid item xs={12} sm={6} style={{ padding: '20px 50px', textAlign: 'justify', }}>
                                <UpgradeMessage />
                            </Grid>
                            <Grid item xs={12} sm={6} style={{ padding: '20px 50px' }}>
                                <div style={{ textAlign: 'justify' }}>
                                    <h3>Purchase a subscription for $9/year!</h3>
                                    <p>Purchasing a subscription will remove the ads from the app and will help us stay up and running!</p>
                                </div>
                                <Elements stripe={stripePromise}>
                                    <div style={{ padding: 15, borderRadius: 10, border: 'solid 4px #fafafa' }}>
                                        <StripeForm setShowForm={setShowForm} firebase={props.firebase} authUser={authUser} />
                                    </div>
                                </Elements>
                            </Grid>
                        </Grid>
                    </>
                )
            }
            }
        </AuthUserContext.Consumer>
    )
};

class LoginManagementBase extends Component {
    constructor(props) {
        super(props);

        this.state = {
            activeSignInMethods: [],
            error: null,
        };
    }

    render() {
        return (
            <div>
                <button onClick={() => this.props.firebase.doSignOut()}>Log out of this app!!!</button>
            </div>
        );
    }
}

const LoginManagement = withFirebase(LoginManagementBase);

const condition = authUser => !!authUser;

export default compose(
    withEmailVerification,
    withAuthorization(condition),
    withFirebase,
)(AccountPage);
</code>```

答:
You will probably need to look into StripeForm to fix this issue.

What happens in StripeForm after calling setShowForm?

I assume there is some code after setShowForm, but with the redirect from setShowForm being called: Grid, Elements and StripeForm components are unmounted and it gives you this warning.

If this is actually your issue, setShowForm should be the last thing you do in StripeForm when it's meant to redirect.

A similar case with Formik, where you have this warning:

Warning: Can't perform a React state update on an unmounted component.
  This is a no-op, but it indicates a memory leak in your application.
  To fix, cancel all subscriptions and asynchronous tasks in a useEffect
  cleanup function.

When you submit your form you call some action to save it, once it's done Formik needs to know it's done with setSubmitting(false);.

That's how it goes :

```<code>callSomeSaveAction(...)
.then(...)
.catch(...)
.finally(() => setSubmitting(false));
</code>```

It works fine until you decide to use a redirect in callSomeSaveAction.then

This happens because the redirect unmount the formik component but setSubmitting is called anyway.

Hopefully you can fix you issue with something like this.
Since I know that the component will be unmounted thanks to the redirect, I don't need setSubmitting(false) when I redirect, but I still need it in case an error occured:

```<code>callSomeSaveAction(...)
.then(...)
.catch(() => {
    ...
    setSubmitting(false);
});
</code>```

Body:
I have a component where I'm giving my users an option to subscribe to remove ads from the app. I integrated Stripe perfectly until I came to the redirect portion of the app. Since I don't want to have people create multiple subscriptions if my users have an active subscription (which I'm getting from firebase db), then I want to redirect my users to another page. This is causing me to see a warning about memory leaks once the redirect takes place. This doesn't happen anymore after trying to navigate back to the subscription component. Here's my component stripped away with most code that doesn't cause the error to show. I figured it was stripe elements because If I remove the call to that component, then all works great, and no memory leaks. Has anyone ever experienced this issue and have a fix?

I feel like it has to do with the way I'm setting the show form using the React.useEffect hook. Any help is truly appreciated!

import React, { Component } from 'react';
import { compose } from 'recompose';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import { Redirect } from 'react-router-dom';
import StripeForm from '../components/StripeForm';
import Grid from '@material-ui/core/Grid';

import {
    AuthUserContext,
    withAuthorization,
    withEmailVerification,
} from '../components/Session';
import { withFirebase } from '../components/Firebase';
const stripePromise = loadStripe('stripe-key-here');

const AccountPage = (props) => {
    const show = props.firebase.userData.stripe.subscriptions.subscription.plan.active
    const [showForm, setShowForm] = React.useState(show)

    React.useEffect(() => {
        if (show !== showForm) {
            setShowForm(show);
        }
    }, [show, showForm])

    return (

        <AuthUserContext.Consumer>
            {authUser => {
                return (
                    <>
                        {showForm ? <Redirect to="/thank-you" /> : null}
                        <Grid container spacing={3} style={{ background: '#fff', maxWidth: '94%', margin: '20px auto', borderRadius: 7 }}>
                            <Grid item xs={12} sm={6} style={{ padding: '20px 50px', textAlign: 'justify', }}>
                                <UpgradeMessage />
                            </Grid>
                            <Grid item xs={12} sm={6} style={{ padding: '20px 50px' }}>

Purchase a subscription for $9/year!

Purchasing a subscription will remove the ads from the app and will help us stay up and running!

                                <Elements stripe={stripePromise}>

                                        <StripeForm setShowForm={setShowForm} firebase={props.firebase} authUser={authUser} />

                                </Elements>
                            </Grid>
                        </Grid>
                    </>
                )
            }
            }
        </AuthUserContext.Consumer>
    )
};

class LoginManagementBase extends Component {
    constructor(props) {
        super(props);

        this.state = {
            activeSignInMethods: [],
            error: null,
        };
    }

    render() {
        return (

                <button onClick={() => this.props.firebase.doSignOut()}>Log out of this app!!!</button>

        );
    }
}

const LoginManagement = withFirebase(LoginManagementBase);

const condition = authUser => !!authUser;

export default compose(
    withEmailVerification,
    withAuthorization(condition),
    withFirebase,
)(AccountPage);

Body:
You will probably need to look into StripeForm to fix this issue.

What happens in StripeForm after calling setShowForm?

I assume there is some code after setShowForm, but with the redirect from setShowForm being called: Grid, Elements and StripeForm components are unmounted and it gives you this warning.

If this is actually your issue, setShowForm should be the last thing you do in StripeForm when it's meant to redirect.

A similar case with Formik, where you have this warning:

Warning: Can't perform a React state update on an unmounted component.
  This is a no-op, but it indicates a memory leak in your application.
  To fix, cancel all subscriptions and asynchronous tasks in a useEffect
  cleanup function.

When you submit your form you call some action to save it, once it's done Formik needs to know it's done with setSubmitting(false);.

That's how it goes :

callSomeSaveAction(...)
.then(...)
.catch(...)
.finally(() => setSubmitting(false));

It works fine until you decide to use a redirect in callSomeSaveAction.then

This happens because the redirect unmount the formik component but setSubmitting is called anyway.

Hopefully you can fix you issue with something like this.
Since I know that the component will be unmounted thanks to the redirect, I don't need setSubmitting(false) when I redirect, but I still need it in case an error occured:

callSomeSaveAction(...)
.then(...)
.catch(() => {
    ...
    setSubmitting(false);
});


来源: stackexchange

问:
basemap: How to remove actual lat/lon lines while keeping the ticks on the axis
I plotted a map by basemap as below:

```<code>plt.figure(figsize=(7,6))
m = Basemap(projection='cyl',llcrnrlat=40.125,urcrnrlat=44.625,\
        llcrnrlon=-71.875,urcrnrlon=-66.375,resolution='h')
m.drawparallels(np.arange(int(40.125),int(44.625),1),labels=[1,0,0,0])
m.drawmeridians(np.arange(int(-71.875),int(-66.375),1),labels=[0,0,0,1])
m.drawcoastlines()
m.fillcontinents(color='grey')
m.drawmapboundary()
</code>```

The picture as below:

How can I remove actual lat/lon lines while keeping the ticks on the axis?

答:
I found the basemap ticks setting quite confusing.

The figure below shows 8 different setups. Some notations:

ST=T: suppress_ticks=True.

ST=F: suppress_ticks=False.

DP-DR: drawparallels() and drawmeridians().

DP-DR(LW=0): drawparallels(...,linewidth=0) and drawmeridians(...,linewidth=0).

mill: miller map projection.

Interpret the results in the top panel:

(a): This is the same as the OP's figure, i.e. using suppress_ticks=True (the default) and drawparallels() and drawmeridians().

(b): Solution suggested by @Greg, setting linewidth=0 to drawparallels() and drawmeridians() removes the grid lines, but not adding the ticks. Note the title of the question is "How to remove actual lat/lon lines while keeping the ticks on the axis".

(c): Solution suggested by @Janusz. Note that setting suppress_ticks=False alone does not remove the grid lines, instead it adds an extra set of ticks. That's why suppress_ticks is default to True.

(d): Combine (b) and (c). linewidth=0 is what actually removes the grid lines. Again suppress_ticks=False introduces extra ticks, and they overlap with ticks added by drawparallels() and drawmeridians().

2nd panel:

(e): What if we don't use drawparallels() and drawmeridians() and let it automatically add ticks? The 1st drawback is that you don't get to control which ticks to add. Another one is the tick labels are formatted without the W/E, N/S symbols (if you add labelstyle='+/-' to drawparallels() or drawmeridians(), the labels will use + 41^{\circ} format). And there is another big drawback, as shown in (f).

(f): This is using mill map projection instead of cyl. Notice the automatic labeling uses meter as unit rather than degree of latitude/longitude. Not good (at least in this case).

(g): This is trying to add the tickmarks by manually setting ticks, by ax.set_xticks(lon_ticks) and ax.set_yticks(lat_ticks). The ticks are added, but labels overlap.

(h): This is my proposed solution again using mill projection:

```<code>m = Basemap(projection='mill',llcrnrlat=40.125,urcrnrlat=44.625,\
        llcrnrlon=-71.875,urcrnrlon=-66.375,resolution='l',
        ax=ax8, fix_aspect=False,
        suppress_ticks=True)

m.drawcoastlines()

lat_ticks=np.arange(np.ceil(40.125),int(44.625),1)
lon_ticks=np.arange(np.ceil(-71.875),int(-66.375),1)

# convert from degree to map projection
lon_ticks_proj, _=m(lon_ticks, np.zeros(len(lon_ticks)))
_, lat_ticks_proj=m(np.zeros(len(lat_ticks)), lat_ticks)
# manually add ticks
ax8.set_xticks(lon_ticks_proj)
ax8.set_yticks(lat_ticks_proj)
ax8.tick_params(axis='both',which='major')
# add ticks to the opposite side as well
ax8.xaxis.set_ticks_position('both')
ax8.yaxis.set_ticks_position('both')
# remove the tick labels
ax8.xaxis.set_ticklabels([])
ax8.yaxis.set_ticklabels([])

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0,
        xoffset=0.03*abs(m.xmax-m.xmin)) # need to enlarge the offset a bit
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0,
        yoffset=0.03*abs(m.ymax-m.ymin)) # need to enlarge the offset a bit
</code>```

Finally, the script to create the figure:

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

def getBM(ax, suppress_ticks, projection='cyl'):
    m = Basemap(projection=projection,llcrnrlat=40.125,urcrnrlat=44.625,\
            llcrnrlon=-71.875,urcrnrlon=-66.375,resolution='l',
            ax=ax, fix_aspect=False,
            suppress_ticks=suppress_ticks)

    m.drawcoastlines()

    return m

lat_ticks=np.arange(np.ceil(40.125),int(44.625),1)
lon_ticks=np.arange(np.ceil(-71.875),int(-66.375),1)

figure=plt.figure(figsize=(14,7),dpi=100)
nrows=2; ncols=4

#------------------------s1------------------------
ax1=figure.add_subplot(nrows,ncols,1)
m = getBM(ax1, True)

m.drawparallels(lat_ticks,labels=[1,0,0,0])
m.drawmeridians(lon_ticks,labels=[0,0,0,1])
ax1.set_title('(a) ST=T, DP-DR')

#------------------------s2------------------------
ax2=figure.add_subplot(nrows,ncols,2)
m = getBM(ax2, True)

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0)
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0)
ax2.set_title('(b) ST=T, DP-DR(LW=0)')

#------------------------s3------------------------
ax3=figure.add_subplot(nrows,ncols,3)
m = getBM(ax3, False)

m.drawparallels(lat_ticks,labels=[1,0,0,0])
m.drawmeridians(lon_ticks,labels=[0,0,0,1])
ax3.set_title('(c) ST=F, DP-DR')

#------------------------s4------------------------
ax4=figure.add_subplot(nrows,ncols,4)
m = getBM(ax4, False)

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0)
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0)
ax4.set_title('(d) ST=F, DP-DR(LW=0)')

#------------------------s5------------------------
ax5=figure.add_subplot(nrows,ncols,5)
m = getBM(ax5, False)

ax5.set_title('(e) ST=F')

#------------------------s6------------------------
ax6=figure.add_subplot(nrows,ncols,6)
m = getBM(ax6, False, projection='mill')

ax6.set_title('(f) ST=F, mill')

#------------------------s7------------------------
ax7=figure.add_subplot(nrows,ncols,7)
m = getBM(ax7, True)

ax7.set_xticks(lon_ticks)
ax7.set_yticks(lat_ticks)
m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0)
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0)
ax7.set_title('(g) ST=T, DP-DR(LW=0), manual tick')

#------------------------s8------------------------
ax8=figure.add_subplot(nrows,ncols,8)
m = getBM(ax8, True, projection='mill')

# convert from degree to map projection
lon_ticks_proj, _=m(lon_ticks, np.zeros(len(lon_ticks)))
_, lat_ticks_proj=m(np.zeros(len(lat_ticks)), lat_ticks)
# manually add ticks
ax8.set_xticks(lon_ticks_proj)
ax8.set_yticks(lat_ticks_proj)
ax8.tick_params(axis='both',which='major')
# add ticks to the opposite side as well
ax8.xaxis.set_ticks_position('both')
ax8.yaxis.set_ticks_position('both')
# remove the tick labels
ax8.xaxis.set_ticklabels([])
ax8.yaxis.set_ticklabels([])

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0,
        xoffset=0.03*abs(m.xmax-m.xmin)) # need to enlarge the offset a bit
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0,
        yoffset=0.03*abs(m.ymax-m.ymin)) # need to enlarge the offset a bit
ax8.set_title('(g) ST=T, DP-DR(LW=0), manual tick*')

figure.tight_layout()
figure.show()
</code>```

UPDATE: I'm having some issues with saved PDF files when using drawparallels(..., linewidth=0) and drawmeridians(..., linewidth=0). More details are given at https://github.com/matplotlib/basemap/issues/493.

If you have the similar issue, consider using drawparallels(..., zorder=-2) instead.

ContentLicense: CC BY-SA 3.0

Body:
I plotted a map by basemap as below:

plt.figure(figsize=(7,6))
m = Basemap(projection='cyl',llcrnrlat=40.125,urcrnrlat=44.625,\
        llcrnrlon=-71.875,urcrnrlon=-66.375,resolution='h')
m.drawparallels(np.arange(int(40.125),int(44.625),1),labels=[1,0,0,0])
m.drawmeridians(np.arange(int(-71.875),int(-66.375),1),labels=[0,0,0,1])
m.drawcoastlines()
m.fillcontinents(color='grey')
m.drawmapboundary()

The picture as below:

How can I remove actual lat/lon lines while keeping the ticks on the axis?

Body:
I found the basemap ticks setting quite confusing.

The figure below shows 8 different setups. Some notations:

ST=T: suppress_ticks=True.

ST=F: suppress_ticks=False.

DP-DR: drawparallels() and drawmeridians().

DP-DR(LW=0): drawparallels(...,linewidth=0) and drawmeridians(...,linewidth=0).

mill: miller map projection.

Interpret the results in the top panel:

(a): This is the same as the OP's figure, i.e. using suppress_ticks=True (the default) and drawparallels() and drawmeridians().

(b): Solution suggested by @Greg, setting linewidth=0 to drawparallels() and drawmeridians() removes the grid lines, but not adding the ticks. Note the title of the question is "How to remove actual lat/lon lines while keeping the ticks on the axis".

(c): Solution suggested by @Janusz. Note that setting suppress_ticks=False alone does not remove the grid lines, instead it adds an extra set of ticks. That's why suppress_ticks is default to True.

(d): Combine (b) and (c). linewidth=0 is what actually removes the grid lines. Again suppress_ticks=False introduces extra ticks, and they overlap with ticks added by drawparallels() and drawmeridians().

2nd panel:

(e): What if we don't use drawparallels() and drawmeridians() and let it automatically add ticks? The 1st drawback is that you don't get to control which ticks to add. Another one is the tick labels are formatted without the W/E, N/S symbols (if you add labelstyle='+/-' to drawparallels() or drawmeridians(), the labels will use + 41^{\circ} format). And there is another big drawback, as shown in (f).

(f): This is using mill map projection instead of cyl. Notice the automatic labeling uses meter as unit rather than degree of latitude/longitude. Not good (at least in this case).

(g): This is trying to add the tickmarks by manually setting ticks, by ax.set_xticks(lon_ticks) and ax.set_yticks(lat_ticks). The ticks are added, but labels overlap.

(h): This is my proposed solution again using mill projection:

m = Basemap(projection='mill',llcrnrlat=40.125,urcrnrlat=44.625,\
        llcrnrlon=-71.875,urcrnrlon=-66.375,resolution='l',
        ax=ax8, fix_aspect=False,
        suppress_ticks=True)

m.drawcoastlines()

lat_ticks=np.arange(np.ceil(40.125),int(44.625),1)
lon_ticks=np.arange(np.ceil(-71.875),int(-66.375),1)

# convert from degree to map projection
lon_ticks_proj, _=m(lon_ticks, np.zeros(len(lon_ticks)))
_, lat_ticks_proj=m(np.zeros(len(lat_ticks)), lat_ticks)
# manually add ticks
ax8.set_xticks(lon_ticks_proj)
ax8.set_yticks(lat_ticks_proj)
ax8.tick_params(axis='both',which='major')
# add ticks to the opposite side as well
ax8.xaxis.set_ticks_position('both')
ax8.yaxis.set_ticks_position('both')
# remove the tick labels
ax8.xaxis.set_ticklabels([])
ax8.yaxis.set_ticklabels([])

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0,
        xoffset=0.03*abs(m.xmax-m.xmin)) # need to enlarge the offset a bit
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0,
        yoffset=0.03*abs(m.ymax-m.ymin)) # need to enlarge the offset a bit

Finally, the script to create the figure:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

def getBM(ax, suppress_ticks, projection='cyl'):
    m = Basemap(projection=projection,llcrnrlat=40.125,urcrnrlat=44.625,\
            llcrnrlon=-71.875,urcrnrlon=-66.375,resolution='l',
            ax=ax, fix_aspect=False,
            suppress_ticks=suppress_ticks)

    m.drawcoastlines()

    return m

lat_ticks=np.arange(np.ceil(40.125),int(44.625),1)
lon_ticks=np.arange(np.ceil(-71.875),int(-66.375),1)

figure=plt.figure(figsize=(14,7),dpi=100)
nrows=2; ncols=4

#------------------------s1------------------------
ax1=figure.add_subplot(nrows,ncols,1)
m = getBM(ax1, True)

m.drawparallels(lat_ticks,labels=[1,0,0,0])
m.drawmeridians(lon_ticks,labels=[0,0,0,1])
ax1.set_title('(a) ST=T, DP-DR')

#------------------------s2------------------------
ax2=figure.add_subplot(nrows,ncols,2)
m = getBM(ax2, True)

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0)
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0)
ax2.set_title('(b) ST=T, DP-DR(LW=0)')

#------------------------s3------------------------
ax3=figure.add_subplot(nrows,ncols,3)
m = getBM(ax3, False)

m.drawparallels(lat_ticks,labels=[1,0,0,0])
m.drawmeridians(lon_ticks,labels=[0,0,0,1])
ax3.set_title('(c) ST=F, DP-DR')

#------------------------s4------------------------
ax4=figure.add_subplot(nrows,ncols,4)
m = getBM(ax4, False)

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0)
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0)
ax4.set_title('(d) ST=F, DP-DR(LW=0)')

#------------------------s5------------------------
ax5=figure.add_subplot(nrows,ncols,5)
m = getBM(ax5, False)

ax5.set_title('(e) ST=F')

#------------------------s6------------------------
ax6=figure.add_subplot(nrows,ncols,6)
m = getBM(ax6, False, projection='mill')

ax6.set_title('(f) ST=F, mill')

#------------------------s7------------------------
ax7=figure.add_subplot(nrows,ncols,7)
m = getBM(ax7, True)

ax7.set_xticks(lon_ticks)
ax7.set_yticks(lat_ticks)
m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0)
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0)
ax7.set_title('(g) ST=T, DP-DR(LW=0), manual tick')

#------------------------s8------------------------
ax8=figure.add_subplot(nrows,ncols,8)
m = getBM(ax8, True, projection='mill')

# convert from degree to map projection
lon_ticks_proj, _=m(lon_ticks, np.zeros(len(lon_ticks)))
_, lat_ticks_proj=m(np.zeros(len(lat_ticks)), lat_ticks)
# manually add ticks
ax8.set_xticks(lon_ticks_proj)
ax8.set_yticks(lat_ticks_proj)
ax8.tick_params(axis='both',which='major')
# add ticks to the opposite side as well
ax8.xaxis.set_ticks_position('both')
ax8.yaxis.set_ticks_position('both')
# remove the tick labels
ax8.xaxis.set_ticklabels([])
ax8.yaxis.set_ticklabels([])

m.drawparallels(lat_ticks,labels=[1,0,0,0],linewidth=0,
        xoffset=0.03*abs(m.xmax-m.xmin)) # need to enlarge the offset a bit
m.drawmeridians(lon_ticks,labels=[0,0,0,1],linewidth=0,
        yoffset=0.03*abs(m.ymax-m.ymin)) # need to enlarge the offset a bit
ax8.set_title('(g) ST=T, DP-DR(LW=0), manual tick*')

figure.tight_layout()
figure.show()

UPDATE: I'm having some issues with saved PDF files when using drawparallels(..., linewidth=0) and drawmeridians(..., linewidth=0). More details are given at https://github.com/matplotlib/basemap/issues/493.

If you have the similar issue, consider using drawparallels(..., zorder=-2) instead.

ContentLicense: CC BY-SA 4.0


问:
Assigning values to cross selection of MultiIndex DataFrame (ellipsis style of numpy)
In numpy we can select the last axis with ellipsis indexing, f.i. array[..., 4].

In Pandas DataFrames for structuring large amounts of data, I like to use MultiIndex (which I see as some kind of additional dimensions of the DataFrame). If I want to select a given subset of a DataFrame df, in this case all columns 'key' in the last level of the columns MultiIndex, I can do it with the cross selection method xs:

```<code># create sample multiindex dataframe
mi = pd.MultiIndex.from_product((('a', 'b', 'c'), (1, 2), ('some', 'key', 'foo')))
data = pd.DataFrame(data=np.random.rand(20, 18), columns=mi)

# make cross selection:
xs_df = data.xs('key', axis=1, level=-1)
</code>```

But if I want to assign values to the cross selection, xs won't work.

The documentation proposes to use IndexSlice to access and set values to a cross selection:

```<code>idx = pd.IndexSlice
data.loc[:, idx[:, :, 'key']] *= 10
</code>```

Which is working well as long as I explicitly enter the number of levels by inserting the correct amount of : before 'key'.

Assuming I just want to give the number of levels to a selection function or f.i. always select the last level, independent of the number of levels of the DataFrame, this won't work (afaik).

My current workaround is using None slices for n_levels to skip:

```<code>n_levels = data.columns.nlevels - 1  # assuming I want to select the last level
data.loc[:, (*n_levels*[slice(None)], 'key')] *= 100
</code>```

This is imho a quite nasty and cumbersome workaround. Is there any more pythonic/nicer/better way?

答:
I feel like we can do update and pass drop_level with xs

```<code>data.update(data.xs('key',level=-1,axis=1,drop_level=False)*10)
</code>```

Body:
In numpy we can select the last axis with ellipsis indexing, f.i. array[..., 4].

In Pandas DataFrames for structuring large amounts of data, I like to use MultiIndex (which I see as some kind of additional dimensions of the DataFrame). If I want to select a given subset of a DataFrame df, in this case all columns 'key' in the last level of the columns MultiIndex, I can do it with the cross selection method xs:

# create sample multiindex dataframe
mi = pd.MultiIndex.from_product((('a', 'b', 'c'), (1, 2), ('some', 'key', 'foo')))
data = pd.DataFrame(data=np.random.rand(20, 18), columns=mi)

# make cross selection:
xs_df = data.xs('key', axis=1, level=-1)

But if I want to assign values to the cross selection, xs won't work.

The documentation proposes to use IndexSlice to access and set values to a cross selection:

idx = pd.IndexSlice
data.loc[:, idx[:, :, 'key']] *= 10

Which is working well as long as I explicitly enter the number of levels by inserting the correct amount of : before 'key'.

Assuming I just want to give the number of levels to a selection function or f.i. always select the last level, independent of the number of levels of the DataFrame, this won't work (afaik).

My current workaround is using None slices for n_levels to skip:

n_levels = data.columns.nlevels - 1  # assuming I want to select the last level
data.loc[:, (*n_levels*[slice(None)], 'key')] *= 100

This is imho a quite nasty and cumbersome workaround. Is there any more pythonic/nicer/better way?

Body:
I feel like we can do update and pass drop_level with xs

data.update(data.xs('key',level=-1,axis=1,drop_level=False)*10)


问:
Dynamic attributes in hibernate mapping from front-end
I am trying to insert JSON data to our database using Spring Boot, Hibernate and Angular. The attribute name in this JSON data is unknown at compile time.

Is there any possibility we can use an ORM to insert this data?

答:
You can use @JsonAnySetter. This decorator lets you to define a method in your model class which will receive unrecognized fields. Serialize them and write them in another field. Later, use @JsonAnyGetter for reading your data.

Pseudo-code:

```<code>  @ElementCollection
  @CollectionTable(name = "table")
  @MapKeyColumn(name = "key")
  @Column(name = "value")
  @JsonIgnore
  private Map<String, String> any;
  .
  .
  @JsonAnySetter
  public void setAny(String name, String value) {
    any.put(name, value);
  }
  .
  .
  @JsonAnyGetter
  public Map<String, Object> getAny() {
    return any;
  }
</code>```

Body:
You can use @JsonAnySetter. This decorator lets you to define a method in your model class which will receive unrecognized fields. Serialize them and write them in another field. Later, use @JsonAnyGetter for reading your data.

Pseudo-code:

  @ElementCollection
  @CollectionTable(name = "table")
  @MapKeyColumn(name = "key")
  @Column(name = "value")
  @JsonIgnore
  private Map<String, String> any;
  .
  .
  @JsonAnySetter
  public void setAny(String name, String value) {
    any.put(name, value);
  }
  .
  .
  @JsonAnyGetter
  public Map<String, Object> getAny() {
    return any;
  }


问:
White Space Showing Up on Navigation - SafeView
Previously, I was using toggling to handle navigation. Now I am switching to useNavigation hooks. From one page, I move to another page like this:

```<code><TouchableOpacity
      onPress={() => {
        if (title == 'h') {
          navigation.navigate('AddFriend');
        }
      }}>
</code>```

When In navigate to the screen, I see an unwanted white space at the bottom, even though the original design did not have this. However, when I click the Cancelbutton, the space disappear, the page formats according to what it should be like and then it navigates back to the original page. Why is it showing the white space? How can I remove it?

This is how the code for my AddFriend page looks like:

```<code>type AddFriendPageProps = {
  toggleShowPage: () => void;
  showAddFriendPage: boolean;
};

export const AddFriendPage: React.FunctionComponent<AddFriendPageProps> = ({
  toggleShowPage,
  showAddFriendPage,
}) => {
  const [showAddFriendPhonePage, setShowAddFriendPhonePage] = useState(false);
  const navigation = useNavigation();

  const toggleAddFriendPhonePage = () => {
    setShowAddFriendPhonePage(showAddFriendPhonePage ? false : true);
  };

  return (
    <Modal
    visible={showAddFriendPage}
    animationType="slide" transparent={true}>
      <SafeAreaView>
        <View style={styles.container}>
          <View style={styles.searchTopContainer}>
            <View style={styles.searchTopTextContainer}>
              <Text
                style={styles.searchCancelDoneText}
                onPress={() => navigation.navigate('Home')}
                >
                Cancel
              </Text>
              <Text style={styles.searchTopMiddleText}>Add Friend</Text>
              <Text style={styles.searchCancelDoneText}>Done</Text>
            </View>
            <View style={styles.searchFieldContainer}>
              <View style={styles.buttonContainer}>
                <Button
                  rounded
                  style={styles.button}
                  onPress={() => setShowAddFriendPhonePage(true)}>
                  <Text style={styles.text}>Add by Phone Number</Text>
                </Button>
              </View>
            </View>
          </View>
          <AddFriendPhonePage
            showAddFriendPhonePage={showAddFriendPhonePage}
            toggleShowPage={toggleAddFriendPhonePage}
          />
        </View>
      </SafeAreaView>
    </Modal>
  );
};
</code>```

Styles:

```<code>const styles = ScaledSheet.create({
  container: {
    height: '100%',
    backgroundColor: 'white', //'#2E3331',
    width: '100%',
  },
  searchTopContainer: {
    backgroundColor: '#2E3331',
    height: moderateScale(750),
  },
  searchTopTextContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginVertical: moderateScale(15),
    height: moderateScale(30),
    paddingLeft: moderateScale(30),
    paddingRight: moderateScale(30),
  },
  searchCancelDoneText: {
    fontSize: moderateScale(14),
    color: 'white',
  },
  searchTopMiddleText: {
    fontSize: moderateScale(15),
    fontWeight: 'bold',
    color: 'white',
  },
  searchFieldContainer: {
    alignItems: 'center',
    height: moderateScale(120),
  },
  button: {
    width: moderateScale(200),
    height: moderateScale(50),
    backgroundColor: '#31C283',
    justifyContent: 'center',
    marginBottom: 20,
  },
  text: {
    fontSize: moderateScale(14, 0.7),
  },
  searchField: {
    backgroundColor: 'white',
    width: moderateScale(300, 0.3),
    height: verticalScale(40),
    marginVertical: moderateScale(6),
    borderRadius: verticalScale(10),
  },
  buttonContainer: {
    paddingTop: 250,
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  inputText: {
    color: '#ffffff',
  },
  searchText: {
    fontSize: moderateScale(14),
  },
});
</code>```

If I change the background color the container to red and apply that style on the safeView, it makes the top part (where the time is written) red along with the bottom part which is supposed to match with the other screen. Both come under the safeView thing. How do I separate them?

If I remove the SafeView, the whole screen moves upwards, apart from the Cancel and Done button. The white space increases even more

答:
that white space is added by safeAreaView. if you want the safeAreaView to have the same green background color you have to set the styles on it or it's parent, you currently only have styles on the child View element with the styles.container

I dont understand what you mean by 'how do i separate them'. basically, if you see the red color appear when you apply styles on the safeAreaView then instead of red use the gray/green color on the safeAreaView (that you're already using for the rest of the screen) so that it looks seamless.

Body:
Previously, I was using toggling to handle navigation. Now I am switching to useNavigation hooks. From one page, I move to another page like this:

<TouchableOpacity
      onPress={() => {
        if (title == 'h') {
          navigation.navigate('AddFriend');
        }
      }}>

When In navigate to the screen, I see an unwanted white space at the bottom, even though the original design did not have this. However, when I click the Cancelbutton, the space disappear, the page formats according to what it should be like and then it navigates back to the original page. Why is it showing the white space? How can I remove it?

This is how the code for my AddFriend page looks like:

type AddFriendPageProps = {
  toggleShowPage: () => void;
  showAddFriendPage: boolean;
};

export const AddFriendPage: React.FunctionComponent<AddFriendPageProps> = ({
  toggleShowPage,
  showAddFriendPage,
}) => {
  const [showAddFriendPhonePage, setShowAddFriendPhonePage] = useState(false);
  const navigation = useNavigation();

  const toggleAddFriendPhonePage = () => {
    setShowAddFriendPhonePage(showAddFriendPhonePage ? false : true);
  };

  return (
    <Modal
    visible={showAddFriendPage}
    animationType="slide" transparent={true}>
      <SafeAreaView>
        <View style={styles.container}>
          <View style={styles.searchTopContainer}>
            <View style={styles.searchTopTextContainer}>
              <Text
                style={styles.searchCancelDoneText}
                onPress={() => navigation.navigate('Home')}
                >
                Cancel
              </Text>
              <Text style={styles.searchTopMiddleText}>Add Friend</Text>
              <Text style={styles.searchCancelDoneText}>Done</Text>
            </View>
            <View style={styles.searchFieldContainer}>
              <View style={styles.buttonContainer}>
                <Button
                  rounded
                  style={styles.button}
                  onPress={() => setShowAddFriendPhonePage(true)}>
                  <Text style={styles.text}>Add by Phone Number</Text>
                </Button>
              </View>
            </View>
          </View>
          <AddFriendPhonePage
            showAddFriendPhonePage={showAddFriendPhonePage}
            toggleShowPage={toggleAddFriendPhonePage}
          />
        </View>
      </SafeAreaView>
    </Modal>
  );
};

Styles:

const styles = ScaledSheet.create({
  container: {
    height: '100%',
    backgroundColor: 'white', //'#2E3331',
    width: '100%',
  },
  searchTopContainer: {
    backgroundColor: '#2E3331',
    height: moderateScale(750),
  },
  searchTopTextContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginVertical: moderateScale(15),
    height: moderateScale(30),
    paddingLeft: moderateScale(30),
    paddingRight: moderateScale(30),
  },
  searchCancelDoneText: {
    fontSize: moderateScale(14),
    color: 'white',
  },
  searchTopMiddleText: {
    fontSize: moderateScale(15),
    fontWeight: 'bold',
    color: 'white',
  },
  searchFieldContainer: {
    alignItems: 'center',
    height: moderateScale(120),
  },
  button: {
    width: moderateScale(200),
    height: moderateScale(50),
    backgroundColor: '#31C283',
    justifyContent: 'center',
    marginBottom: 20,
  },
  text: {
    fontSize: moderateScale(14, 0.7),
  },
  searchField: {
    backgroundColor: 'white',
    width: moderateScale(300, 0.3),
    height: verticalScale(40),
    marginVertical: moderateScale(6),
    borderRadius: verticalScale(10),
  },
  buttonContainer: {
    paddingTop: 250,
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  inputText: {
    color: '#ffffff',
  },
  searchText: {
    fontSize: moderateScale(14),
  },
});

If I change the background color the container to red and apply that style on the safeView, it makes the top part (where the time is written) red along with the bottom part which is supposed to match with the other screen. Both come under the safeView thing. How do I separate them?

If I remove the SafeView, the whole screen moves upwards, apart from the Cancel and Done button. The white space increases even more


问:
Choosing values from rdflib
i am new to rdflib and i am using it to run queries on a simple turtle file the data that i am parsing is as follows

<http://www.siemens.com/ai/plant/data/PolishingStation1> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "PolishingStation1" .
<http://www.siemens.com/ai/plant/data/PolishingStation2> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "PolishingStation2" .
<http://www.siemens.com/ai/plant/data/QuenchingStation1> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation1" .
<http://www.siemens.com/ai/plant/data/QuenchingStation2> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation2" .
<http://www.siemens.com/ai/plant/data/QuenchingStation3> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation3" .
<http://www.siemens.com/ai/plant/data/QuenchingStation4> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation4" .

and the query is as follows

`SELECT  ?name ?type
From
WHERE
{

```<code>?MaterialFlowObject a ns1:Drain.
?MaterialFlowObject a ?type.
?MaterialFlowObject ns1:hasName ?name.
#?Parameter ns1:hasParameter    ?parameters .
</code>```

}`

the problem is when i get the type i get 2 values per variable and i cannot separate them at all, the code that i am using

kg = ConjunctiveGraph()
 input_ontology_path = "./plant_data.ttl"
 kg.parse(input_ontology_path, format="ttl")

with open("queries/get_Material_Flow.rq") as f:
         sparql_query_string = f.read()
         query_output = kg.query(sparql_query_string)
         for row in query_output:
            d = str( (row['type'] ))
           s = d.split('#')[-1]
           print(s)
            # pprint.pprint(row)

The result that i am getting is always a string containing both values
Drain
MaterialFlowObject
in one string and i cannot separate them with split string or anything else, all i need is to get Drain in a variable different from MaterialFlowObject is there anyway

答:
With your sample files fixed up:

plant_data.ttl:

```<code>@prefix ns1: <tag:a#> .

<http://www.siemens.com/ai/plant/data/PolishingStation1>
    a ns1:Station;
    a ns1:MaterialFlowObject;
    ns1:hasName "PolishingStation1" .
...
</code>```

get_Material_Flow.rq:

```<code>PREFIX ns1: <tag:a#>

SELECT ?name ?type
WHERE {
  ?MaterialFlowObject a ns1:Station.
  ?MaterialFlowObject a ?type.
  ?MaterialFlowObject ns1:hasName ?name.
}
</code>```

run_query.py:

```<code>from rdflib.graph import ConjunctiveGraph

kg = ConjunctiveGraph()
input_ontology_path = "./plant_data.ttl"
kg.parse(input_ontology_path, format="ttl")

with open("get_Material_Flow.rq") as f:
    sparql_query_string = f.read()
    query_output = kg.query(sparql_query_string)
    for row in query_output:
        print(f'name={str(row["name"])},type={str(row["type"])}')
</code>```

This works as expected, and produces a result for each match:

```<code>name=PolishingStation1,type=tag:a#Station
name=PolishingStation1,type=tag:a#MaterialFlowObject
name=QuenchingStation3,type=tag:a#MaterialFlowObject
name=QuenchingStation3,type=tag:a#Station
name=QuenchingStation4,type=tag:a#Station
name=QuenchingStation4,type=tag:a#MaterialFlowObject
name=PolishingStation2,type=tag:a#MaterialFlowObject
name=PolishingStation2,type=tag:a#Station
name=QuenchingStation2,type=tag:a#MaterialFlowObject
name=QuenchingStation2,type=tag:a#Station
name=QuenchingStation1,type=tag:a#MaterialFlowObject
name=QuenchingStation1,type=tag:a#Station
</code>```

Title: Choosing values from rdflib

Body:
i am new to rdflib and i am using it to run queries on a simple turtle file the data that i am parsing is as follows

<http://www.siemens.com/ai/plant/data/PolishingStation1> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "PolishingStation1" .
<http://www.siemens.com/ai/plant/data/PolishingStation2> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "PolishingStation2" .
<http://www.siemens.com/ai/plant/data/QuenchingStation1> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation1" .
<http://www.siemens.com/ai/plant/data/QuenchingStation2> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation2" .
<http://www.siemens.com/ai/plant/data/QuenchingStation3> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation3" .
<http://www.siemens.com/ai/plant/data/QuenchingStation4> a ns1:Station a ns1:MaterialFlowObject;
    ns1:hasName "QuenchingStation4" .

and the query is as follows

`SELECT  ?name ?type
From
WHERE
{

?MaterialFlowObject a ns1:Drain.
?MaterialFlowObject a ?type.
?MaterialFlowObject ns1:hasName ?name.
#?Parameter ns1:hasParameter    ?parameters .

}`

the problem is when i get the type i get 2 values per variable and i cannot separate them at all, the code that i am using

kg = ConjunctiveGraph()
 input_ontology_path = "./plant_data.ttl"
 kg.parse(input_ontology_path, format="ttl")

with open("queries/get_Material_Flow.rq") as f:
         sparql_query_string = f.read()
         query_output = kg.query(sparql_query_string)
         for row in query_output:
            d = str( (row['type'] ))
           s = d.split('#')[-1]
           print(s)
            # pprint.pprint(row)

The result that i am getting is always a string containing both values
Drain
MaterialFlowObject
in one string and i cannot separate them with split string or anything else, all i need is to get Drain in a variable different from MaterialFlowObject is there anyway

Body:
With your sample files fixed up:

plant_data.ttl:

@prefix ns1: <tag:a#> .

<http://www.siemens.com/ai/plant/data/PolishingStation1>
    a ns1:Station;
    a ns1:MaterialFlowObject;
    ns1:hasName "PolishingStation1" .
...

get_Material_Flow.rq:

PREFIX ns1: <tag:a#>

SELECT ?name ?type
WHERE {
  ?MaterialFlowObject a ns1:Station.
  ?MaterialFlowObject a ?type.
  ?MaterialFlowObject ns1:hasName ?name.
}

run_query.py:

from rdflib.graph import ConjunctiveGraph

kg = ConjunctiveGraph()
input_ontology_path = "./plant_data.ttl"
kg.parse(input_ontology_path, format="ttl")

with open("get_Material_Flow.rq") as f:
    sparql_query_string = f.read()
    query_output = kg.query(sparql_query_string)
    for row in query_output:
        print(f'name={str(row["name"])},type={str(row["type"])}')

This works as expected, and produces a result for each match:

name=PolishingStation1,type=tag:a#Station
name=PolishingStation1,type=tag:a#MaterialFlowObject
name=QuenchingStation3,type=tag:a#MaterialFlowObject
name=QuenchingStation3,type=tag:a#Station
name=QuenchingStation4,type=tag:a#Station
name=QuenchingStation4,type=tag:a#MaterialFlowObject
name=PolishingStation2,type=tag:a#MaterialFlowObject
name=PolishingStation2,type=tag:a#Station
name=QuenchingStation2,type=tag:a#MaterialFlowObject
name=QuenchingStation2,type=tag:a#Station
name=QuenchingStation1,type=tag:a#MaterialFlowObject
name=QuenchingStation1,type=tag:a#Station


问:
Android: having stack trace error after using sharedprefs for login session
First I wanted the user to login and once login it wont go back to login screen until logout. So i added sharedPrefs. I was able to play around login>mainActivity then exit the app and open the app it would open mainActivity instead of login screen. Next I would logout and it would go back to login screen. As soon as I am in login screen I would exit the app and reopen the icon app and it would give an error. Another thing is when logout into the login screen and i press cancel button it would also give an error. I must have messed up the stack around but couldn't find the solution. I included the logcat below which shows the part where i could not login anymore.

Login.java

```<code>public class Login extends Activity {
    //protected static final SharedPreferences settings = null;
    private EditText etUsername;
    private Button btnLogin;
    private Button btnCancel;
    private TextView lblResult;
    private String username;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //replaces the default 'Back' button action
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {
            this.startActivity(new Intent(Login.this,Login.class));
        }
        return true;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("username", username);

        if(prefs.getString("username", null)!=null)
        {Intent i = new Intent(getApplicationContext(), Customer.class);
        startActivity(i);}

        etUsername = (EditText)findViewById(R.id.username);
        btnLogin = (Button)findViewById(R.id.login_button);
        btnCancel = (Button)findViewById(R.id.cancel_button);
        lblResult = (TextView)findViewById(R.id.result);

        btnLogin.setOnClickListener(new OnClickListener() {
            //@Override
            public void onClick(View v) {
            // Check Login
            String username = etUsername.getText().toString();

            if(username.equals("1111")){
                lblResult.setText("Login successful.");

                Intent i = new Intent(getApplicationContext(), Customer.class);
                startActivity(i);
btnCancel.setOnClickListener(new OnClickListener() {

                @Override
            public void onClick(View v) {
               // Close the application
            finish();
</code>```

Logout.java

```<code>public class LogoutActivity extends Activity {
    private Button btnLogout;
    private Button btnCancel;
    private TextView lblResult;
    private EditText code;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //replaces the default 'Back' button action
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {
             this.startActivity(new Intent(LogoutActivity.this,Customer.class));
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logout);

        code = (EditText)findViewById(R.id.codeout);
        btnLogout = (Button) findViewById(R.id.submit);
        btnCancel = (Button) findViewById(R.id.cancel);
        lblResult = (TextView)findViewById(R.id.result);

        btnLogout.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String logout = code.getText().toString();

                if (logout.equals("99")){
                    lblResult.setText("Logout successful");

                    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = settings.edit();
                    editor.remove("username");

                    Intent i = new Intent(getApplicationContext(), Login.class);
                    startActivity(i);

                    finish();

                } else {
                    lblResult.setText("Logout failed");
                }}});
         btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), Customer.class);
                startActivity(i);
}
</code>```

Manifest.xml

```<code><application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Login"
            android:noHistory="true"
            android:excludeFromRecents="true"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
 .............
        <activity android:name=".LogoutActivity"
        android:noHistory="true"
            android:excludeFromRecents="true"
            android:label="Logout"></activity>
</code>```

Customer.java

```<code>import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Customer extends ListActivity
{

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //replaces the default 'Back' button action
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {
            this.startActivity(new Intent(Customer.this,Customer.class));
        }
        return true;
    }
    TextView selection;
    CustomerListItem[] items = {
            new CustomerListItem("Start Trip", StartTripActivity.class),
            new CustomerListItem("Clock in", ClockinActivity.class),
            new CustomerListItem("Customer Svc", CustomerSvcActivity.class),
            new CustomerListItem("Independent Inspection", InspectionActivity.class),
            new CustomerListItem("Pick Up", PickUpActivity.class),
            new CustomerListItem("Log Out", LogoutActivity.class)};
    private TextView resultsTxt;

    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.customer);
        setListAdapter(new ArrayAdapter<CustomerListItem>(
                this, android.R.layout.simple_list_item_1, items));
        selection = (TextView) findViewById(R.id.selection);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        super.onListItemClick(l, v, position, id);
        final Intent intent = new Intent(this, items[position].getActivity());
        startActivityForResult(intent, position);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK)
        {
                switch (requestCode)
            {
                case 0:
                    // TODO: handle the return of the StartTripActivity
                    break;
                case 1:
                    // TODO: handle the return of the ClockinActivity
                    break;
                case 2:
                    // TODO: handle the return of the CustomerSvcActivity
                case 3:
                    // TODO: handle the return of the InspectionActivity
                    break;
                case 4:
                    // TODO: handle the return of the PickUpActivity
                    break;
                case 5:
                    // TODO: handle the return of the LogoutActivity
                    break;
                default:
                    break;
            }
        }
        else if (resultCode == RESULT_CANCELED)
        {
            resultsTxt.setText("Canceled");
        }
    }
}
</code>```

Logcat

```<code> 06-02 07:01:16.981: DEBUG/dalvikvm(981): GC freed 4479 objects / 199288 bytes in 104ms
06-02 07:01:20.632: WARN/KeyCharacterMap(2878): Bad keycharmap - filesize=32
06-02 07:01:20.632: WARN/KeyCharacterMap(2878): Error loading keycharmap file '/system/usr/keychars/qtouch-touchscreen.kcm.bin'. hw.keyboards.0.devname='qtouch-touchscreen'
06-02 07:01:20.632: WARN/KeyCharacterMap(2878): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-02 07:01:25.362: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:01:26.281: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.Customer} }
06-02 07:01:26.621: DEBUG/dalvikvm(959): GC freed 1008 objects / 58176 bytes in 180ms
06-02 07:01:26.681: INFO/ActivityManager(900): Displayed activity com.errill2/.Customer: 399 ms
06-02 07:01:30.121: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:01:38.941: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.LogoutActivity} }
06-02 07:01:39.281: INFO/ActivityManager(900): Displayed activity com.merrill2/.LogoutActivity: 330 ms
06-02 07:01:43.071: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.Login} }
06-02 07:01:43.631: DEBUG/OpenSSLSessionImpl(900): Freeing OpenSSL session
06-02 07:01:43.640: DEBUG/dalvikvm(900): GC freed 23770 objects / 1125392 bytes in 299ms
06-02 07:01:43.681: INFO/ActivityManager(900): Displayed activity com.merrill2/.Login: 606 ms
06-02 07:01:45.601: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.HOME} flags=0x10200000 comp={com.android.launcher/com.android.launcher.Launcher} }
06-02 07:01:45.781: WARN/IInputConnectionWrapper(2878): showStatusIcon on inactive InputConnection
06-02 07:01:47.475: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.LAUNCHER} flags=0x10200000 comp={com.merrill2/com.merrill2.Login} }
06-02 07:01:47.501: DEBUG/AndroidRuntime(2878): Shutting down VM
06-02 07:01:47.501: WARN/dalvikvm(2878): threadid=3: thread exiting with uncaught exception (group=0x40013140)
06-02 07:01:47.501: ERROR/AndroidRuntime(2878): Uncaught handler: thread main exiting due to uncaught exception
06-02 07:01:47.521: ERROR/AndroidRuntime(2878): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3026)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3068)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.access$2300(ActivityThread.java:128)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1739)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.os.Looper.loop(Looper.java:123)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.main(ActivityThread.java:3992)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at dalvik.system.NativeStart.main(Native Method)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878): Caused by: java.lang.NullPointerException
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at com.merrill2.Customer.onActivityResult(Customer.java:90)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.Activity.dispatchActivityResult(Activity.java:3595)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3022)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     ... 11 more
06-02 07:01:47.531: INFO/Process(900): Sending signal. PID: 2878 SIG: 3
06-02 07:01:47.551: INFO/dalvikvm(2878): threadid=7: reacting to signal 3
06-02 07:01:47.571: INFO/dalvikvm(2878): Wrote stack trace to '/data/anr/traces.txt'
06-02 07:01:50.482: INFO/Process(2878): Sending signal. PID: 2878 SIG: 9
06-02 07:01:50.501: INFO/ActivityManager(900): Process com.merrill2 (pid 2878) has died.
06-02 07:01:50.501: INFO/WindowManager(900): WIN DEATH: Window{437941d8 com.merrill2/com.merrill2.Customer paused=false}
06-02 07:01:50.501: INFO/WindowManager(900): WIN DEATH: Window{43877980 com.merrill2/com.merrill2.Login paused=true}
06-02 07:01:50.561: WARN/InputManagerService(900): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@435e6fe8
06-02 07:01:54.363: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:01:55.740: DEBUG/dalvikvm(1225): GC freed 315 objects / 13368 bytes in 90ms
</code>```

Debug Logcat

```<code>06-02 07:57:53.868: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.LogoutActivity} }
06-02 07:57:54.228: INFO/ActivityManager(900): Displayed activity com.merrill2/.LogoutActivity: 360 ms
06-02 07:57:56.968: DEBUG/dalvikvm(959): GC freed 985 objects / 56696 bytes in 86ms
06-02 07:57:57.669: WARN/KeyCharacterMap(2895): Bad keycharmap - filesize=32
06-02 07:57:57.669: WARN/KeyCharacterMap(2895): Error loading keycharmap file '/system/usr/keychars/qtouch-touchscreen.kcm.bin'. hw.keyboards.0.devname='qtouch-touchscreen'
06-02 07:57:57.669: WARN/KeyCharacterMap(2895): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-02 07:57:58.628: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.Login} }
06-02 07:57:58.768: DEBUG/dalvikvm(2895): GC freed 1710 objects / 109536 bytes in 87ms
06-02 07:57:59.118: INFO/ActivityManager(900): Displayed activity com.merrill2/.Login: 493 ms
06-02 07:58:02.565: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:58:05.438: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.HOME} flags=0x10200000 comp={com.android.launcher/com.android.launcher.Launcher} }
06-02 07:58:05.668: WARN/IInputConnectionWrapper(2895): showStatusIcon on inactive InputConnection
06-02 07:58:06.568: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.LAUNCHER} flags=0x10200000 comp={com.merrill2/com.merrill2.Login} }
06-02 07:58:06.588: DEBUG/AndroidRuntime(2895): Shutting down VM
06-02 07:58:06.588: WARN/dalvikvm(2895): threadid=3: thread exiting with uncaught exception (group=0x40013140)
06-02 07:58:06.588: ERROR/AndroidRuntime(2895): Uncaught handler: thread main exiting due to uncaught exception
06-02 07:58:06.598: ERROR/AndroidRuntime(2895): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3026)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3068)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.access$2300(ActivityThread.java:128)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1739)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.os.Looper.loop(Looper.java:123)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.main(ActivityThread.java:3992)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at dalvik.system.NativeStart.main(Native Method)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895): Caused by: java.lang.NullPointerException
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at com.merrill2.Customer.onActivityResult(Customer.java:90)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.Activity.dispatchActivityResult(Activity.java:3595)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3022)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     ... 11 more
06-02 07:58:06.638: INFO/Process(900): Sending signal. PID: 2895 SIG: 3
06-02 07:58:06.638: INFO/dalvikvm(2895): threadid=7: reacting to signal 3
06-02 07:58:06.668: INFO/dalvikvm(2895): Wrote stack trace to '/data/anr/traces.txt'
06-02 07:58:08.600: INFO/Process(2895): Sending signal. PID: 2895 SIG: 9
06-02 07:58:08.618: INFO/ActivityManager(900): Process com.merrill2 (pid 2895) has died.
06-02 07:58:08.628: INFO/WindowManager(900): WIN DEATH: Window{43748a70 com.merrill2/com.merrill2.Customer paused=false}
06-02 07:58:08.638: INFO/ActivityManager(900): Start proc com.merrill2 for activity com.merrill2/.Customer: pid=2932 uid=10053 gids={1006, 3003}
06-02 07:58:08.698: INFO/jdwp(2932): received file descriptor 10 from ADB
06-02 07:58:08.718: WARN/System.err(2932): Can't dispatch DDM chunk 46454154: no handler defined
06-02 07:58:08.728: WARN/System.err(2932): Can't dispatch DDM chunk 4d505251: no handler defined
06-02 07:58:08.918: DEBUG/dalvikvm(900): threadid=13: bogus mon 1+0>0; adjusting
06-02 07:58:08.918: DEBUG/dalvikvm(900): GC freed 24573 objects / 1334712 bytes in 275ms
06-02 07:58:08.938: INFO/WindowManager(900): WIN DEATH: Window{4368b128 com.merrill2/com.merrill2.Login paused=true}
06-02 07:58:09.178: DEBUG/AndroidRuntime(2932): Shutting down VM
06-02 07:58:09.178: WARN/dalvikvm(2932): threadid=3: thread exiting with uncaught exception (group=0x40013140)
06-02 07:58:09.178: ERROR/AndroidRuntime(2932): Uncaught handler: thread main exiting due to uncaught exception
06-02 07:58:09.188: ERROR/AndroidRuntime(2932): java.lang.RuntimeException: Unable to resume activity {com.merrill2/com.merrill2.Customer}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2653)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2668)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2308)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.access$1800(ActivityThread.java:128)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1710)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.os.Looper.loop(Looper.java:123)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.main(ActivityThread.java:3992)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at dalvik.system.NativeStart.main(Native Method)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3026)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2637)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     ... 12 more
06-02 07:58:09.188: ERROR/AndroidRuntime(2932): Caused by: java.lang.NullPointerException
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at com.merrill2.Customer.onActivityResult(Customer.java:90)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.Activity.dispatchActivityResult(Activity.java:3595)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3022)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     ... 13 more
06-02 07:58:09.228: INFO/Process(900): Sending signal. PID: 2932 SIG: 3
06-02 07:58:09.228: INFO/dalvikvm(2932): threadid=7: reacting to signal 3
06-02 07:58:09.248: INFO/dalvikvm(2932): Wrote stack trace to '/data/anr/traces.txt'
06-02 07:58:12.538: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:58:16.577: WARN/ActivityManager(900): Launch timeout has expired, giving up wake lock!
06-02 07:58:18.971: WARN/ActivityManager(900): Activity idle timeout for HistoryRecord{43610e18 {com.merrill2/com.merrill2.Customer}}
06-02 07:58:24.058: DEBUG/dalvikvm(1225): GC freed 270 objects / 10200 bytes in 90ms
06-02 07:58:29.088: DEBUG/dalvikvm(981): GC freed 688 objects / 28808 bytes in 112ms
06-02 07:59:01.598: DEBUG/PowerManagerService(900): setPowerState: mPowerState=3 newState=1 noChangeLights=false
</code>```

答:
From the trace, it appears that you need to have a listview in your XML with an id like this:

android:id="@android:id/list"

Body:
First I wanted the user to login and once login it wont go back to login screen until logout. So i added sharedPrefs. I was able to play around login>mainActivity then exit the app and open the app it would open mainActivity instead of login screen. Next I would logout and it would go back to login screen. As soon as I am in login screen I would exit the app and reopen the icon app and it would give an error. Another thing is when logout into the login screen and i press cancel button it would also give an error. I must have messed up the stack around but couldn't find the solution. I included the logcat below which shows the part where i could not login anymore.

Login.java

public class Login extends Activity {
    //protected static final SharedPreferences settings = null;
    private EditText etUsername;
    private Button btnLogin;
    private Button btnCancel;
    private TextView lblResult;
    private String username;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //replaces the default 'Back' button action
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {
            this.startActivity(new Intent(Login.this,Login.class));
        }
        return true;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("username", username);

        if(prefs.getString("username", null)!=null)
        {Intent i = new Intent(getApplicationContext(), Customer.class);
        startActivity(i);}

        etUsername = (EditText)findViewById(R.id.username);
        btnLogin = (Button)findViewById(R.id.login_button);
        btnCancel = (Button)findViewById(R.id.cancel_button);
        lblResult = (TextView)findViewById(R.id.result);

        btnLogin.setOnClickListener(new OnClickListener() {
            //@Override
            public void onClick(View v) {
            // Check Login
            String username = etUsername.getText().toString();

            if(username.equals("1111")){
                lblResult.setText("Login successful.");

                Intent i = new Intent(getApplicationContext(), Customer.class);
                startActivity(i);
btnCancel.setOnClickListener(new OnClickListener() {

                @Override
            public void onClick(View v) {
               // Close the application
            finish();

Logout.java

public class LogoutActivity extends Activity {
    private Button btnLogout;
    private Button btnCancel;
    private TextView lblResult;
    private EditText code;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //replaces the default 'Back' button action
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {
             this.startActivity(new Intent(LogoutActivity.this,Customer.class));
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logout);

        code = (EditText)findViewById(R.id.codeout);
        btnLogout = (Button) findViewById(R.id.submit);
        btnCancel = (Button) findViewById(R.id.cancel);
        lblResult = (TextView)findViewById(R.id.result);

        btnLogout.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String logout = code.getText().toString();

                if (logout.equals("99")){
                    lblResult.setText("Logout successful");

                    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = settings.edit();
                    editor.remove("username");

                    Intent i = new Intent(getApplicationContext(), Login.class);
                    startActivity(i);

                    finish();

                } else {
                    lblResult.setText("Logout failed");
                }}});
         btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), Customer.class);
                startActivity(i);
}

Manifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Login"
            android:noHistory="true"
            android:excludeFromRecents="true"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
 .............
        <activity android:name=".LogoutActivity"
        android:noHistory="true"
            android:excludeFromRecents="true"
            android:label="Logout"></activity>

Customer.java

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Customer extends ListActivity
{

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //replaces the default 'Back' button action
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {
            this.startActivity(new Intent(Customer.this,Customer.class));
        }
        return true;
    }
    TextView selection;
    CustomerListItem[] items = {
            new CustomerListItem("Start Trip", StartTripActivity.class),
            new CustomerListItem("Clock in", ClockinActivity.class),
            new CustomerListItem("Customer Svc", CustomerSvcActivity.class),
            new CustomerListItem("Independent Inspection", InspectionActivity.class),
            new CustomerListItem("Pick Up", PickUpActivity.class),
            new CustomerListItem("Log Out", LogoutActivity.class)};
    private TextView resultsTxt;

    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.customer);
        setListAdapter(new ArrayAdapter<CustomerListItem>(
                this, android.R.layout.simple_list_item_1, items));
        selection = (TextView) findViewById(R.id.selection);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        super.onListItemClick(l, v, position, id);
        final Intent intent = new Intent(this, items[position].getActivity());
        startActivityForResult(intent, position);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK)
        {
                switch (requestCode)
            {
                case 0:
                    // TODO: handle the return of the StartTripActivity
                    break;
                case 1:
                    // TODO: handle the return of the ClockinActivity
                    break;
                case 2:
                    // TODO: handle the return of the CustomerSvcActivity
                case 3:
                    // TODO: handle the return of the InspectionActivity
                    break;
                case 4:
                    // TODO: handle the return of the PickUpActivity
                    break;
                case 5:
                    // TODO: handle the return of the LogoutActivity
                    break;
                default:
                    break;
            }
        }
        else if (resultCode == RESULT_CANCELED)
        {
            resultsTxt.setText("Canceled");
        }
    }
}

Logcat

 06-02 07:01:16.981: DEBUG/dalvikvm(981): GC freed 4479 objects / 199288 bytes in 104ms
06-02 07:01:20.632: WARN/KeyCharacterMap(2878): Bad keycharmap - filesize=32
06-02 07:01:20.632: WARN/KeyCharacterMap(2878): Error loading keycharmap file '/system/usr/keychars/qtouch-touchscreen.kcm.bin'. hw.keyboards.0.devname='qtouch-touchscreen'
06-02 07:01:20.632: WARN/KeyCharacterMap(2878): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-02 07:01:25.362: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:01:26.281: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.Customer} }
06-02 07:01:26.621: DEBUG/dalvikvm(959): GC freed 1008 objects / 58176 bytes in 180ms
06-02 07:01:26.681: INFO/ActivityManager(900): Displayed activity com.errill2/.Customer: 399 ms
06-02 07:01:30.121: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:01:38.941: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.LogoutActivity} }
06-02 07:01:39.281: INFO/ActivityManager(900): Displayed activity com.merrill2/.LogoutActivity: 330 ms
06-02 07:01:43.071: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.Login} }
06-02 07:01:43.631: DEBUG/OpenSSLSessionImpl(900): Freeing OpenSSL session
06-02 07:01:43.640: DEBUG/dalvikvm(900): GC freed 23770 objects / 1125392 bytes in 299ms
06-02 07:01:43.681: INFO/ActivityManager(900): Displayed activity com.merrill2/.Login: 606 ms
06-02 07:01:45.601: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.HOME} flags=0x10200000 comp={com.android.launcher/com.android.launcher.Launcher} }
06-02 07:01:45.781: WARN/IInputConnectionWrapper(2878): showStatusIcon on inactive InputConnection
06-02 07:01:47.475: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.LAUNCHER} flags=0x10200000 comp={com.merrill2/com.merrill2.Login} }
06-02 07:01:47.501: DEBUG/AndroidRuntime(2878): Shutting down VM
06-02 07:01:47.501: WARN/dalvikvm(2878): threadid=3: thread exiting with uncaught exception (group=0x40013140)
06-02 07:01:47.501: ERROR/AndroidRuntime(2878): Uncaught handler: thread main exiting due to uncaught exception
06-02 07:01:47.521: ERROR/AndroidRuntime(2878): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3026)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3068)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.access$2300(ActivityThread.java:128)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1739)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.os.Looper.loop(Looper.java:123)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.main(ActivityThread.java:3992)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at dalvik.system.NativeStart.main(Native Method)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878): Caused by: java.lang.NullPointerException
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at com.merrill2.Customer.onActivityResult(Customer.java:90)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.Activity.dispatchActivityResult(Activity.java:3595)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3022)
06-02 07:01:47.521: ERROR/AndroidRuntime(2878):     ... 11 more
06-02 07:01:47.531: INFO/Process(900): Sending signal. PID: 2878 SIG: 3
06-02 07:01:47.551: INFO/dalvikvm(2878): threadid=7: reacting to signal 3
06-02 07:01:47.571: INFO/dalvikvm(2878): Wrote stack trace to '/data/anr/traces.txt'
06-02 07:01:50.482: INFO/Process(2878): Sending signal. PID: 2878 SIG: 9
06-02 07:01:50.501: INFO/ActivityManager(900): Process com.merrill2 (pid 2878) has died.
06-02 07:01:50.501: INFO/WindowManager(900): WIN DEATH: Window{437941d8 com.merrill2/com.merrill2.Customer paused=false}
06-02 07:01:50.501: INFO/WindowManager(900): WIN DEATH: Window{43877980 com.merrill2/com.merrill2.Login paused=true}
06-02 07:01:50.561: WARN/InputManagerService(900): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@435e6fe8
06-02 07:01:54.363: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:01:55.740: DEBUG/dalvikvm(1225): GC freed 315 objects / 13368 bytes in 90ms

Debug Logcat

06-02 07:57:53.868: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.LogoutActivity} }
06-02 07:57:54.228: INFO/ActivityManager(900): Displayed activity com.merrill2/.LogoutActivity: 360 ms
06-02 07:57:56.968: DEBUG/dalvikvm(959): GC freed 985 objects / 56696 bytes in 86ms
06-02 07:57:57.669: WARN/KeyCharacterMap(2895): Bad keycharmap - filesize=32
06-02 07:57:57.669: WARN/KeyCharacterMap(2895): Error loading keycharmap file '/system/usr/keychars/qtouch-touchscreen.kcm.bin'. hw.keyboards.0.devname='qtouch-touchscreen'
06-02 07:57:57.669: WARN/KeyCharacterMap(2895): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-02 07:57:58.628: INFO/ActivityManager(900): Starting activity: Intent { comp={com.merrill2/com.merrill2.Login} }
06-02 07:57:58.768: DEBUG/dalvikvm(2895): GC freed 1710 objects / 109536 bytes in 87ms
06-02 07:57:59.118: INFO/ActivityManager(900): Displayed activity com.merrill2/.Login: 493 ms
06-02 07:58:02.565: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:58:05.438: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.HOME} flags=0x10200000 comp={com.android.launcher/com.android.launcher.Launcher} }
06-02 07:58:05.668: WARN/IInputConnectionWrapper(2895): showStatusIcon on inactive InputConnection
06-02 07:58:06.568: INFO/ActivityManager(900): Starting activity: Intent { action=android.intent.action.MAIN categories={android.intent.category.LAUNCHER} flags=0x10200000 comp={com.merrill2/com.merrill2.Login} }
06-02 07:58:06.588: DEBUG/AndroidRuntime(2895): Shutting down VM
06-02 07:58:06.588: WARN/dalvikvm(2895): threadid=3: thread exiting with uncaught exception (group=0x40013140)
06-02 07:58:06.588: ERROR/AndroidRuntime(2895): Uncaught handler: thread main exiting due to uncaught exception
06-02 07:58:06.598: ERROR/AndroidRuntime(2895): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3026)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3068)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.access$2300(ActivityThread.java:128)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1739)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.os.Looper.loop(Looper.java:123)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.main(ActivityThread.java:3992)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at dalvik.system.NativeStart.main(Native Method)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895): Caused by: java.lang.NullPointerException
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at com.merrill2.Customer.onActivityResult(Customer.java:90)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.Activity.dispatchActivityResult(Activity.java:3595)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3022)
06-02 07:58:06.598: ERROR/AndroidRuntime(2895):     ... 11 more
06-02 07:58:06.638: INFO/Process(900): Sending signal. PID: 2895 SIG: 3
06-02 07:58:06.638: INFO/dalvikvm(2895): threadid=7: reacting to signal 3
06-02 07:58:06.668: INFO/dalvikvm(2895): Wrote stack trace to '/data/anr/traces.txt'
06-02 07:58:08.600: INFO/Process(2895): Sending signal. PID: 2895 SIG: 9
06-02 07:58:08.618: INFO/ActivityManager(900): Process com.merrill2 (pid 2895) has died.
06-02 07:58:08.628: INFO/WindowManager(900): WIN DEATH: Window{43748a70 com.merrill2/com.merrill2.Customer paused=false}
06-02 07:58:08.638: INFO/ActivityManager(900): Start proc com.merrill2 for activity com.merrill2/.Customer: pid=2932 uid=10053 gids={1006, 3003}
06-02 07:58:08.698: INFO/jdwp(2932): received file descriptor 10 from ADB
06-02 07:58:08.718: WARN/System.err(2932): Can't dispatch DDM chunk 46454154: no handler defined
06-02 07:58:08.728: WARN/System.err(2932): Can't dispatch DDM chunk 4d505251: no handler defined
06-02 07:58:08.918: DEBUG/dalvikvm(900): threadid=13: bogus mon 1+0>0; adjusting
06-02 07:58:08.918: DEBUG/dalvikvm(900): GC freed 24573 objects / 1334712 bytes in 275ms
06-02 07:58:08.938: INFO/WindowManager(900): WIN DEATH: Window{4368b128 com.merrill2/com.merrill2.Login paused=true}
06-02 07:58:09.178: DEBUG/AndroidRuntime(2932): Shutting down VM
06-02 07:58:09.178: WARN/dalvikvm(2932): threadid=3: thread exiting with uncaught exception (group=0x40013140)
06-02 07:58:09.178: ERROR/AndroidRuntime(2932): Uncaught handler: thread main exiting due to uncaught exception
06-02 07:58:09.188: ERROR/AndroidRuntime(2932): java.lang.RuntimeException: Unable to resume activity {com.merrill2/com.merrill2.Customer}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2653)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2668)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2308)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.access$1800(ActivityThread.java:128)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1710)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.os.Looper.loop(Looper.java:123)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.main(ActivityThread.java:3992)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at dalvik.system.NativeStart.main(Native Method)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=0, data=null} to activity {com.merrill2/com.merrill2.Customer}: java.lang.NullPointerException
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3026)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2637)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     ... 12 more
06-02 07:58:09.188: ERROR/AndroidRuntime(2932): Caused by: java.lang.NullPointerException
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at com.merrill2.Customer.onActivityResult(Customer.java:90)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.Activity.dispatchActivityResult(Activity.java:3595)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3022)
06-02 07:58:09.188: ERROR/AndroidRuntime(2932):     ... 13 more
06-02 07:58:09.228: INFO/Process(900): Sending signal. PID: 2932 SIG: 3
06-02 07:58:09.228: INFO/dalvikvm(2932): threadid=7: reacting to signal 3
06-02 07:58:09.248: INFO/dalvikvm(2932): Wrote stack trace to '/data/anr/traces.txt'
06-02 07:58:12.538: DEBUG/DispatchService(946): Handled message = TIMED_SERVICE_UNMASK
06-02 07:58:16.577: WARN/ActivityManager(900): Launch timeout has expired, giving up wake lock!
06-02 07:58:18.971: WARN/ActivityManager(900): Activity idle timeout for HistoryRecord{43610e18 {com.merrill2/com.merrill2.Customer}}
06-02 07:58:24.058: DEBUG/dalvikvm(1225): GC freed 270 objects / 10200 bytes in 90ms
06-02 07:58:29.088: DEBUG/dalvikvm(981): GC freed 688 objects / 28808 bytes in 112ms
06-02 07:59:01.598: DEBUG/PowerManagerService(900): setPowerState: mPowerState=3 newState=1 noChangeLights=false