问:
Mysql column count doesn't Match value count (but it does!)
I am running the following procedure in mysql:

```<code>create procedure addSavingAccount(id int(10), account_number varchar(10))
begin
insert into saving values(id,'savings', account_number, 0);
end //
</code>```

However, when I try to call it, it gives me this error:

```<code>mysql> call addSavingAccount(103, 'B505');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
</code>```

I checked on anything that could be linked to it, including triggers. But everything seems like it should be working. Here is my list of triggers:

```<code>create trigger balance_change_saving after update on saving for each row
begin
if old.balance != new.balance
then

insert into balance_update_history values(null, 'saving', new.account_number, old.balance, new.balance,
                                            (SELECT NOW()), (select USER()));
end if;
end//

create trigger balance_insert_saving after insert on saving for each row
begin
insert into balance_update_history values(null, 'saving', new.account_number, 0, new.balance, (select now()),
                                            (select user()));
end //

create trigger balance_delete_saving after delete on saving for each row
begin
insert into balance_update_history values(null, null, null, old.balance, null,
                                        (SELECT NOW()), (select USER()));
end //
</code>```

And here is where I define the table:

```<code>create table if not exists saving(account_number varchar(10) , customer_id int(10), balance decimal(8,2), primary key(account_number));
</code>```

I'd just really like to to figure this out.

答:
There are three columns based on your table create statement, not four. (what is the last 0 in that insert?)

Also, in the procedure, it appears that your insert values are out-of-order relative to the table creation order?  So you can either rearrange the insert values to match the table, OR specify the columns with the insert.

Body:
I am running the following procedure in mysql:

create procedure addSavingAccount(id int(10), account_number varchar(10))
begin
insert into saving values(id,'savings', account_number, 0);
end //

However, when I try to call it, it gives me this error:

mysql> call addSavingAccount(103, 'B505');
ERROR 1136 (21S01): Column count doesn't match value count at row 1

I checked on anything that could be linked to it, including triggers. But everything seems like it should be working. Here is my list of triggers:

create trigger balance_change_saving after update on saving for each row
begin
if old.balance != new.balance
then

insert into balance_update_history values(null, 'saving', new.account_number, old.balance, new.balance,
                                            (SELECT NOW()), (select USER()));
end if;
end//

create trigger balance_insert_saving after insert on saving for each row
begin
insert into balance_update_history values(null, 'saving', new.account_number, 0, new.balance, (select now()),
                                            (select user()));
end //

create trigger balance_delete_saving after delete on saving for each row
begin
insert into balance_update_history values(null, null, null, old.balance, null,
                                        (SELECT NOW()), (select USER()));
end //

And here is where I define the table:

create table if not exists saving(account_number varchar(10) , customer_id int(10), balance decimal(8,2), primary key(account_number));

I'd just really like to to figure this out.


来源: stackexchange

问:
Getting error while using Stanford Core NLP In java (tokensregex.parser.TokenMgrError)
I am getting this error
Error: edu.stanford.nlp.ling.tokensregex.parser.TokenMgrError:Encountered: "\'", after : ""

I am using latest 2016-10-31 version of stanford core nlp,
Here is my code

```<code>  static MaxentTagger tagger = new MaxentTagger("C:/Users/Sam/Desktop/stanford-corenlp-full-2016-10-31/stanford-corenlp-full-2016-10-31/edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger");

  tokens = new ArrayList<CoreLabel>();
  properties = new Properties();
  properties.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
  pipeline = new StanfordCoreNLP(properties);

  this.sentenceFeatures = Main.pipeline.process(textFeatures)
            .get(CoreAnnotations.SentencesAnnotation.class);
  for(CoreMap sentence: this.sentenceFeatures) {
        // **using TokensRegex**
        for (CoreLabel token: sentence.get(TokensAnnotation.class)){
            Main.tokens.add(token);
        }
        this.p1 = TokenSequencePattern.compile(this.textFeatures);
        this.matcher = p1.getMatcher(Main.tokens);
        for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
            String words = token.get(TextAnnotation.class);
            this.wordsList.add(words);
            String tagged = Main.tagger.tagString(words);
            this.wordsList.add(tagged);
            this.no_of_words++;
            this.no_of_chars += words.length();
        }
  }
</code>```

While

```<code>  textFeatures = "At the western corner of the northern peninsula of Michigan you'll find Porcupine Mountains Wilderness State Park that is a true gem for a great family vacation , and the largest State Park in Michigan too.It has many things to offer to families looking for adventure in the great outdoors.And it's accessible during all the seasons of the year.The Park got its name from the Ojibwa Indians, who named the 'small mountains' thus, because, with their tall trees, they looked like crouching porcupines.Visit in the spring as the leaves begin to bud.Call on it in the summer lambing season.Greet it in the Autumn as the leaves begin to fall.Love it in the winter skying season.Its terrain is wild and rugged where it sits at the shoreline of Lake Superior, and inland where it embraces sixty-thousand acres of towering pines and sturdy birches and natural hemlock forests.The rivers teem with various species of trout as they cut through the forests."
</code>```

and Exception i am getting is:

```<code>Exception in thread "main" java.lang.RuntimeException: When parsing Here are some of Michigan's premier attractions (although of course it's by no means complete) - or intended to be, for that matter.Porcupine Mountains
At the western corner of the northern peninsula of Michigan you'll find Porcupine Mountains Wilderness State Park that is a true gem for a great family vacation , and the largest State Park in Michigan too.It has many things to offer to families looking for adventure in the great outdoors.And it's accessible during all the seasons of the year.The Park got its name from the Ojibwa Indians, who named the 'small mountains' thus, because, with their tall trees, they looked like crouching porcupines.Visit in the spring as the leaves begin to bud.Call on it in the summer lambing season.Greet it in the Autumn as the leaves begin to fall.Love it in the winter skying season.Its terrain is wild and rugged where it sits at the shoreline of Lake Superior, and inland where it embraces sixty-thousand acres of towering pines and sturdy birches and natural hemlock forests.The rivers teem with various species of trout as they cut through the forests.       edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParseException: Parsing failed. Error: edu.stanford.nlp.ling.tokensregex.parser.TokenMgrError: Lexical error at line 1, column 26.  Encountered: "\'" (39), after : ""
at edu.stanford.nlp.ling.tokensregex.TokenSequencePattern.compile(TokenSequencePattern.java:192)
at edu.stanford.nlp.ling.tokensregex.TokenSequencePattern.compile(TokenSequencePattern.java:171)
</code>```

答:
The TokenSequencePattern should be the rules you want to compile, not the text you want to find the patterns in.

Here is a general reference to TokensRegex as well:

https://nlp.stanford.edu/software/tokensregex.html

ContentLicense: CC BY-SA 3.0

Body:
I am getting this error
Error: edu.stanford.nlp.ling.tokensregex.parser.TokenMgrError:Encountered: "\'", after : ""

I am using latest 2016-10-31 version of stanford core nlp,
Here is my code

  static MaxentTagger tagger = new MaxentTagger("C:/Users/Sam/Desktop/stanford-corenlp-full-2016-10-31/stanford-corenlp-full-2016-10-31/edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger");

  tokens = new ArrayList<CoreLabel>();
  properties = new Properties();
  properties.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
  pipeline = new StanfordCoreNLP(properties);

  this.sentenceFeatures = Main.pipeline.process(textFeatures)
            .get(CoreAnnotations.SentencesAnnotation.class);
  for(CoreMap sentence: this.sentenceFeatures) {
        // **using TokensRegex**
        for (CoreLabel token: sentence.get(TokensAnnotation.class)){
            Main.tokens.add(token);
        }
        this.p1 = TokenSequencePattern.compile(this.textFeatures);
        this.matcher = p1.getMatcher(Main.tokens);
        for (CoreLabel token: sentence.get(TokensAnnotation.class)) {
            String words = token.get(TextAnnotation.class);
            this.wordsList.add(words);
            String tagged = Main.tagger.tagString(words);
            this.wordsList.add(tagged);
            this.no_of_words++;
            this.no_of_chars += words.length();
        }
  }

While

  textFeatures = "At the western corner of the northern peninsula of Michigan you'll find Porcupine Mountains Wilderness State Park that is a true gem for a great family vacation , and the largest State Park in Michigan too.It has many things to offer to families looking for adventure in the great outdoors.And it's accessible during all the seasons of the year.The Park got its name from the Ojibwa Indians, who named the 'small mountains' thus, because, with their tall trees, they looked like crouching porcupines.Visit in the spring as the leaves begin to bud.Call on it in the summer lambing season.Greet it in the Autumn as the leaves begin to fall.Love it in the winter skying season.Its terrain is wild and rugged where it sits at the shoreline of Lake Superior, and inland where it embraces sixty-thousand acres of towering pines and sturdy birches and natural hemlock forests.The rivers teem with various species of trout as they cut through the forests."

and Exception i am getting is:

Exception in thread "main" java.lang.RuntimeException: When parsing Here are some of Michigan's premier attractions (although of course it's by no means complete) - or intended to be, for that matter.Porcupine Mountains
At the western corner of the northern peninsula of Michigan you'll find Porcupine Mountains Wilderness State Park that is a true gem for a great family vacation , and the largest State Park in Michigan too.It has many things to offer to families looking for adventure in the great outdoors.And it's accessible during all the seasons of the year.The Park got its name from the Ojibwa Indians, who named the 'small mountains' thus, because, with their tall trees, they looked like crouching porcupines.Visit in the spring as the leaves begin to bud.Call on it in the summer lambing season.Greet it in the Autumn as the leaves begin to fall.Love it in the winter skying season.Its terrain is wild and rugged where it sits at the shoreline of Lake Superior, and inland where it embraces sixty-thousand acres of towering pines and sturdy birches and natural hemlock forests.The rivers teem with various species of trout as they cut through the forests.       edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParseException: Parsing failed. Error: edu.stanford.nlp.ling.tokensregex.parser.TokenMgrError: Lexical error at line 1, column 26.  Encountered: "\'" (39), after : ""
at edu.stanford.nlp.ling.tokensregex.TokenSequencePattern.compile(TokenSequencePattern.java:192)
at edu.stanford.nlp.ling.tokensregex.TokenSequencePattern.compile(TokenSequencePattern.java:171)


问:
Javascript project using Handsontable cannot find module on import
I am trying to use the Handsontable seets component for VueJS project compiled with Webpack. But I am getting a 'cannot find module numbro' error, which occurs even if I dont import numbro in a module. I have installed all packages according to the package.json below using

```<code>npm install
</code>```

package.json:

```<code>"dependencies": {
  "vue": "^2.1.10",
  "handsontable": "^0.31.1",
  "moment": "^2.18.1",
  "numbro": "^1.10.1",
  "pikaday": "^1.5.1",
  "vue-handsontable": "^0.0.2",
  "zeroclipboard": "^2.3.0"
},
</code>```

As mentioned here: https://github.com/handsontable/handsontable/issues/3407 I added the four dependencies of Handsontable to the module loaders section of the webpack config file.

webpack.config.js

```<code>module: {
loaders: [
  {
    test: require.resolve('numbro'),
    loader: 'expose?numbro'
  },
  {
    test: require.resolve('moment'),
    loader: 'expose?moment'
  },
  {
    test: require.resolve('pikaday'),
    loader: 'expose?Pikaday'
  },
  {
    test: require.resolve('zeroclipboard'),
    loader: 'expose?ZeroClipboard'
  }]
</code>```

TableView.vue

```<code><template>
       <div id="hot-preview">
            <cool-table :data="data" :settings="{}"></cool-table>
        </div>
    </div>
</template>

<script>
import moment from 'moment'
import numbro from 'numbro'
import pikaday from 'pikaday'
import Zeroclipboard from 'zeroclipboard'
import Handsontable from 'handsontable'
import CoolTable from 'vue-handsontable'

export default {
  name: 'TablesView',
  data () {
    return {
      data: [
        ['', 'Kia', 'Nissan', 'Toyota', 'Honda'],
        ['2008', 10, 11, 12, 13],
        ['2009', 20, 11, 14, 13],
        ['2010', 30, 15, 12, 13]
      ]
    }
  },
  components: {
    CoolTable
  }
}
</script>
</code>```

When I compile and run my VueJS project I get a console error:

```<code>Error: Cannot find module 'numbro'
</code>```

I can see a numbro folder with numbro.js in the node_modules folder. Any ideas as to what could be going wrong?

答:
To get Handsontable to work I changed the webpack.config.js to use expose-loader:

```<code>loader: 'expose-loader?numbro'
</code>```

Then I installed expose-loader

```<code>npm install expose-loader
</code>```

Body:
I am trying to use the Handsontable seets component for VueJS project compiled with Webpack. But I am getting a 'cannot find module numbro' error, which occurs even if I dont import numbro in a module. I have installed all packages according to the package.json below using

npm install

package.json:

"dependencies": {
  "vue": "^2.1.10",
  "handsontable": "^0.31.1",
  "moment": "^2.18.1",
  "numbro": "^1.10.1",
  "pikaday": "^1.5.1",
  "vue-handsontable": "^0.0.2",
  "zeroclipboard": "^2.3.0"
},

As mentioned here: https://github.com/handsontable/handsontable/issues/3407 I added the four dependencies of Handsontable to the module loaders section of the webpack config file.

webpack.config.js

module: {
loaders: [
  {
    test: require.resolve('numbro'),
    loader: 'expose?numbro'
  },
  {
    test: require.resolve('moment'),
    loader: 'expose?moment'
  },
  {
    test: require.resolve('pikaday'),
    loader: 'expose?Pikaday'
  },
  {
    test: require.resolve('zeroclipboard'),
    loader: 'expose?ZeroClipboard'
  }]

TableView.vue

<template>

            <cool-table :data="data" :settings="{}"></cool-table>

</template>

When I compile and run my VueJS project I get a console error:

Error: Cannot find module 'numbro'

I can see a numbro folder with numbro.js in the node_modules folder. Any ideas as to what could be going wrong?

Body:
To get Handsontable to work I changed the webpack.config.js to use expose-loader:

loader: 'expose-loader?numbro'

Then I installed expose-loader

npm install expose-loader


问:
App wont run unless you update google play services error on real device
I am using Firebase Auth for my app, in some devices it throws me that error, my firebase dependencies are 9.6.1.

1:Can i do something against this?

2:The onComplete never gets called so i cant know if the user doesnt support this, how could i handle it?

3:Are there a lot of devices with version of google play services lower than that?

Thanks

答:
During app initialization, your code should call GoogleApiAvailability.makeGooglePlayServicesAvailable(). The invoked processing:

Attempts to make Google Play services available on this device. If
  Play Services is already available, the returned Task may complete
  immediately.

If it is necessary to display UI in order to complete this request
  (e.g. sending the user to the Google Play store) the passed Activity
  will be used to display this UI.

It is recommended to call this method from onCreate(Bundle). If the
  passed Activity completes before the returned Task completes, the Task
  will fail with a CancellationException.

Example use in onCreate() of  main Activity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this)
        .addOnCompleteListener(this, new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "onComplete: Play Services OKAY");
                } else {
                    // Show the user some UI explaining that the needed version
                    // of Play Services could not be installed and the app can't run.
                }
            }
    });

    ...
}
</code>```

Body:
During app initialization, your code should call GoogleApiAvailability.makeGooglePlayServicesAvailable(). The invoked processing:

Attempts to make Google Play services available on this device. If
  Play Services is already available, the returned Task may complete
  immediately.

If it is necessary to display UI in order to complete this request
  (e.g. sending the user to the Google Play store) the passed Activity
  will be used to display this UI.

It is recommended to call this method from onCreate(Bundle). If the
  passed Activity completes before the returned Task completes, the Task
  will fail with a CancellationException.

Example use in onCreate() of  main Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this)
        .addOnCompleteListener(this, new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "onComplete: Play Services OKAY");
                } else {
                    // Show the user some UI explaining that the needed version
                    // of Play Services could not be installed and the app can't run.
                }
            }
    });

    ...
}


问:
opposite of openURL to close web
How do I close openURL once I open it?

I'm looking at the docs but there's no other method listed

https://developer.apple.com/reference/uikit/uiapplicationdelegate/1623073-application?language=objc

I can open it below

```<code> UIApplication.shared.open(authURL, options: [:], completionHandler:nil)
</code>```

but is there a function to close it programatically

答:
When you call that method, the OS switches to the Safari app and passes it the URL you provided. Once you call that method, you no longer have control and the user has to get back to your app on their own.

You might want to look into presenting a SFSafariViewController instead to keep the user inside your app.

Title: opposite of openURL to close web

Body:
How do I close openURL once I open it?

I'm looking at the docs but there's no other method listed

https://developer.apple.com/reference/uikit/uiapplicationdelegate/1623073-application?language=objc

I can open it below

 UIApplication.shared.open(authURL, options: [:], completionHandler:nil)

but is there a function to close it programatically


问:
How to selected value from dropdownList URL aspx
I have a popupButton (custom component) in my aspx page. (Car.aspx)

This button has a URL that calls a new view. (Color.aspx)

I would like to pass as a URL parameter a selected value from the dropdown on the Car.aspx page

I tried the code below but it does not send the selected value in the request but the text <%:ddlCodMercado.SelectedValue%>

Cars.aspx

```<code><asp:DropDownList id="ddlCodMercado" style="Z-INDEX: 111; LEFT: 10px; POSITION: absolute; TOP: 50px" runat="server" Width="130px" accessKey="R" CssClass="campo" tabIndex="2">
    <asp:ListItem Value="3433">3433</asp:ListItem>
    <asp:ListItem Value="3431">3431</asp:ListItem>
</asp:DropDownList>
<gvs:popupbutton id="pubConcessionaria" style="Z-INDEX: 109; LEFT: 400px; POSITION: absolute; TOP: 50px"
     tabIndex="2" runat="server"  ImageUrl="../img/img_lupa.gif" URL="../Pop-ups/Color_pop.aspx?codMercado=<%:ddlCodMercado.SelectedValue%>"></gvs:popupbutton>
</code>```

How to pass selected value from dropwdown?

答:
Try this;</p>

```<code><asp:DropDownList id="ddlCodMercado" style="Z-INDEX: 111; LEFT: 10px;
POSITION: absolute; TOP: 50px" runat="server" Width="130px" accessKey="R"
CssClass="campo" tabIndex="2">
   <asp:ListItem Value="3433">3433</asp:ListItem>
   <asp:ListItem Value="3431">3431</asp:ListItem>
</asp:DropDownList>

<gvs:popupbutton id="pubConcessionaria" style="Z-INDEX: 109; LEFT: 400px;
POSITION: absolute; TOP: 50px"
tabIndex="2" runat="server"  ImageUrl="../img/img_lupa.gif" URL='<%#
string.Format("../Pop-ups/Color_pop.aspx?codMercado={0}",
ddlCodMercado.SelectedValue) %>'></gvs:popupbutton>
</code>```

Body:
I have a popupButton (custom component) in my aspx page. (Car.aspx)

This button has a URL that calls a new view. (Color.aspx)

I would like to pass as a URL parameter a selected value from the dropdown on the Car.aspx page

I tried the code below but it does not send the selected value in the request but the text <%:ddlCodMercado.SelectedValue%>

Cars.aspx

<asp:DropDownList id="ddlCodMercado" style="Z-INDEX: 111; LEFT: 10px; POSITION: absolute; TOP: 50px" runat="server" Width="130px" accessKey="R" CssClass="campo" tabIndex="2">
    <asp:ListItem Value="3433">3433</asp:ListItem>
    <asp:ListItem Value="3431">3431</asp:ListItem>
</asp:DropDownList>
<gvs:popupbutton id="pubConcessionaria" style="Z-INDEX: 109; LEFT: 400px; POSITION: absolute; TOP: 50px"
     tabIndex="2" runat="server"  ImageUrl="../img/img_lupa.gif" URL="../Pop-ups/Color_pop.aspx?codMercado=<%:ddlCodMercado.SelectedValue%>"></gvs:popupbutton>

How to pass selected value from dropwdown?

Body:
Try this;

<asp:DropDownList id="ddlCodMercado" style="Z-INDEX: 111; LEFT: 10px;
POSITION: absolute; TOP: 50px" runat="server" Width="130px" accessKey="R"
CssClass="campo" tabIndex="2">
   <asp:ListItem Value="3433">3433</asp:ListItem>
   <asp:ListItem Value="3431">3431</asp:ListItem>
</asp:DropDownList>

<gvs:popupbutton id="pubConcessionaria" style="Z-INDEX: 109; LEFT: 400px;
POSITION: absolute; TOP: 50px"
tabIndex="2" runat="server"  ImageUrl="../img/img_lupa.gif" URL='<%#
string.Format("../Pop-ups/Color_pop.aspx?codMercado={0}",
ddlCodMercado.SelectedValue) %>'></gvs:popupbutton>


问:
Elasticsearch Docker stop seems to ignore SIGKILL
I'm trying to use Elasticsearch in Docker for local dev. While I can find containers that work, when docker stop is sent, the containers hang for the default 10s, then docker forcibly kills the container. My assumption here is that ES is either not on PID 1 or other services prevent it from shutting down immediately.

I'm curious if anyone can expand on this, or explain why this is happening more accurately. I'm running numerous tests and 10s+ to shutdown is just annoying when other containers shutdown after 1-2s.

答:
If you don't want to wait the 10 seconds, you can run a docker kill instead of a docker stop. You can also adjust the timeout on docker stop with the -t option, e.g. docker stop -t 2 $container_id to only wait 2 seconds instead of the default 10.

As for why it's ignoring the sigkill, that may depend on what image you are running (there's more than one for elasticsearch). However, if pid 1 is a shell like /bin/sh or /bin/bash, it will not pass signals through. If pid 1 is the elasticsearch process, it may ignore the signal, or 10 seconds may not be long enough for it to fully cleanup and shutdown.


问:
Spinner Value is not preserved for 2nd spinner onStart
I have two spinners, the information on the 2nd spinner is based on the 1st spinner selection
EXAMPLE
SPINNER 1 PROTEIN DAIRY FRUITS
IF SPINNER 1 IS SET WITH PROTEIN then SPINNER 2 EGG CHICKEN
IF SPINNER 1 IS SET WITH FRUITS then SPINNER 2 APPLE ORANGE

Last value selected SPINNER 2 ORANGE

Now I want to preserve the last values selected of the SPINNER1 and SPINNER2, I am using SharedPreferences to accomplish this, it works as expected for SPINNER 1 FRUITS
Position 2 however for SPINNER2 it does not set the last value selected even though the position is correct position 1  when it is called onStart(); it selects the 1st value that is on the array APPLE

Any help would be appreciated

Thanks

```public class TEST extends AppCompatActivity implements View.OnTouchListener {

    SharedPreferences sharedPrefStoreInfo, sharedPrefGetInfo;

    public String keyRow1, getBackInformationRow1;

    String concatenateInfoRow1, currentDateString, concatenateInfoTotals, getBackInformationTotals,
            getBackInformationParseTotals[],

            getBackInformationParseRow1[]

    ;

    // declare adaptors to bind with spinners
    ArrayAdapter<String> spinnerFoodCategoryRow1Adapter;

    // declare the references for the UI elements
    public static Spinner spinnerFoodCategoryRow1,

                spinnerFoodNameRow1,;

    private String[] oilsFoodInformation, fruitsFoodInformation, foodCategoryInformation;

    TextView day, date, textViewProteinRow1, textViewCarbsRow1, textViewFatRow1, textViewCaloriesRow1,

            textViewDailyTotalProtein, textViewDailyTotalCarbs, textViewDailyTotalFat, textViewDailyTotalCalories

    ;

    EditText editRow1;

    String textInputRow1, textInputRow1ResultProtein, textInputRow1ResultCarbs, textInputRow1ResultFat,
            textInputRow1ResultCalories,

            dailyTotalProtein, dailyTotalCarbs, dailyTotalFat, dailyTotalCalories

    ;

    int gramsEditTextInputParseRow1;

    double resultIntProteinRow1, resultIntCaloriesRow1, resultIntCarbsRow1, resultIntFatRow1,;

    double proteinInfoRule3Row1, carbsInfoRule3Row1, fatInfoRule3Row1, caloriesInfoRule3Row1,;

    public String foodNameTempRow1,;

    double canolaProtein = 0;
    double canolaCarbs = 0;
    double canolaFat = 1;
    double canolaCalories = 8.84;
    double coconutOilProtein = 0;
    double coconutOilCarbs = 0;
    double coconutOilFat = 1;
    double coconutOilCalories = 8.62;
    double cornProtein = 0;
    double cornCarbs = 0;
    double cornFat = 1;
    double cornCalories = 9;
    double applesProtein = 0;
    double applesCarbs = 0;
    double applesFat = 0;
    double applesCalories = 0;
    double apricotsProtein = 0;
    double apricotsCarbs = 0;
    double apricotsFat = 0;
    double apricotsCalories = 0;
    double bananasProtein = 0;
    double bananasCarbs = 0;
    double bananasFat = 0;
    double bananasCalories = 0;

    @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.food_tracker_layout); -
            editRow1 = (EditText) findViewById(R.id.editRow1);

            textViewProteinRow1 = (TextView) findViewById(R.id.textViewProteinR1);
            textViewCarbsRow1 = (TextView) findViewById(R.id.textViewCarbsR1);
            textViewFatRow1 = (TextView) findViewById(R.id.textViewFatR1);
            textViewCaloriesRow1 = (TextView) findViewById(R.id.textViewCaloriesR1);

            spinnerFoodCategoryRow1 = (Spinner) findViewById(R.id.spinner1R1);
            spinnerFoodNameRow1 = (Spinner) findViewById(R.id.spinner2R1);

            initializeSpinnerFoodCategoryAdapters();

            // CHANGE THE FONT SIZE OF SPINNER FOOD CATEGORY
            spinnerFoodCategoryRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    // Change the selected item's text color
                    ((TextView) view).setTextColor(Color.BLACK);
                    ((TextView) view).setTextSize(12);

                    getSelectedFoodCategoryRow1(); // **

                    // THIS IS TO CHANGE THE FONT SIZE OF SPINNER FOOD NAME
                    spinnerFoodNameRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            // Change the selected item's text color
                            ((TextView) view).setTextColor(Color.BLACK);
                            ((TextView) view).setTextSize(10);

                            getSelectedFoodNameRow1();

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });// end
                                        } // end

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });

        }// End Main

    public void initializeSpinnerFoodCategoryAdapters() {

        Resources res = getResources();

        spinnerFoodCategoryRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
        spinnerFoodCategoryRow1.setAdapter(spinnerFoodCategoryRow1Adapter);

        spinnerFoodCategoryRow2Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
        spinnerFoodCategoryRow2.setAdapter(spinnerFoodCategoryRow2Adapter);

    }

    public String getSelectedFoodCategoryRow1() {

        Resources res = getResources();

        String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();

        sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

        // FOOD NAME OILS ROW1
        if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0) {

            spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                    res.getStringArray(R.array.SpinnerArrayInfoOils));
            spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);

            int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
            SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
            editor.putInt("ROW1", selectedPosition);
            editor.commit();

            return selectedspinnerFoodCategoryRow1;
        }

        if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 2) {

            spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                    res.getStringArray(R.array.SpinnerArrayInfoFruits));
            spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
            int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
            SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
            editor.putInt("ROW1", selectedPosition);
            editor.commit();

            return selectedspinnerFoodCategoryRow1;
        }

        return selectedspinnerFoodCategoryRow1;

    }

    // RETRIEVE INFO FOODNAME FROM THE SPINNER ROW1
    public String getSelectedFoodNameRow1() {

        Resources res = getResources();

        String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
        String selectedspinnerFoodNameRow1 = (String) spinnerFoodNameRow1.getSelectedItem();

        foodCategoryInformation = res.getStringArray(R.array.SpinnerArrayInfoFoodCategory);

        oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);
        fruitsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoFruits);

        for (int n = 0; n < foodCategoryInformation.length; n++) {

            // SELECTS INFORMATION ON THE FOOD CATEGORY SPINNER
            if (spinnerFoodCategoryRow1.getSelectedItemPosition() == n) {

                // SELECT TYPE OF FOOD CATEGORY
                switch (selectedspinnerFoodCategoryRow1) {

                case "OILS":

                    foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;

                    // ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN OILS
                    for (int i = 0; i < oilsFoodInformation.length; i++) {

                        // SELECT FOOD NAME BASED ON POSITION IN DAIRY
                        if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {

                            SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
                            editor.putInt("ROW1-OILS", i);
                            editor.commit();
                            if (selectedspinnerFoodNameRow1.equals("Canola")) {

                                // ASSIGN THE FOOD NAME SELECTED TO A
                                // foodNameTempRow1 VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                // ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
                                // THE CALCULATION CLICK BUTTON
                                proteinInfoRule3Row1 = canolaProtein;
                                carbsInfoRule3Row1 = canolaCarbs;
                                fatInfoRule3Row1 = canolaFat;
                                caloriesInfoRule3Row1 = canolaCalories;

                            } // end IF CANOLA

                            if (selectedspinnerFoodNameRow1.equals("Coconut Oil")) {

                                // ASSIGN THE FOOD NAME SELECTED TO A
                                // foodNameTempRow1 VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = coconutOilProtein;
                                carbsInfoRule3Row1 = coconutOilCarbs;
                                fatInfoRule3Row1 = coconutOilFat;
                                caloriesInfoRule3Row1 = coconutOilCalories;

                            } // end IF Coconut Oil

                            if (selectedspinnerFoodNameRow1.equals("Corn")) {

                                // ASSIGN THE FOOD NAME SELECTED TO A
                                // foodNameTempRow1 VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = cornProtein;
                                carbsInfoRule3Row1 = cornCarbs;
                                fatInfoRule3Row1 = cornFat;
                                caloriesInfoRule3Row1 = cornCalories;

                            } // end IF Corn

                        } // end if OILS POSITION

                    } // end for OILS

                    break;

                case "FRUITS":

                    // ASSIGN THE FOOD CATEGORY SELECTED TO A
                    // foodCategoryTempRow1 VARIABLE
                    foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;

                    // ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN DAIRY
                    for (int i = 0; i < fruitsFoodInformation.length; i++) {

                        // SELECT FOOD NAME BASED ON POSITION IN DAIRY
                        if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {

                            if (selectedspinnerFoodNameRow1.equals("Apples")) {
                                // ASSIGN THE FOOD SELECTED TO A
                                // foodNameTempRow1Dairy VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                // ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
                                // THE CALCULATION CLICK BUTTON
                                proteinInfoRule3Row1 = applesProtein;
                                carbsInfoRule3Row1 = applesCarbs;
                                fatInfoRule3Row1 = applesFat;
                                caloriesInfoRule3Row1 = applesCalories;

                            } // end if Apples

                            if (selectedspinnerFoodNameRow1.equals("Apricots")) {

                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = apricotsProtein;
                                carbsInfoRule3Row1 = apricotsCarbs;
                                fatInfoRule3Row1 = apricotsFat;
                                caloriesInfoRule3Row1 = apricotsCalories;

                            } // end if Apricots

                            if (selectedspinnerFoodNameRow1.equals("Bananas")) {

                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = bananasProtein;
                                carbsInfoRule3Row1 = bananasCarbs;
                                fatInfoRule3Row1 = bananasFat;
                                caloriesInfoRule3Row1 = bananasCalories;

                            } // end if Bananas

                        } // end if FRUITS POSITION
                    } // end for FRUITS

                    break;

                }// END SWITCH
            } // IF OUTER

        } // OUTER FOR LOOP

        return selectedspinnerFoodNameRow1;

    }// end METHOD GET FOODNAME ROW1

    public boolean onTouch(View v, MotionEvent ev) {
            boolean handledHere = false;

            final int action = ev.getAction();

            final int evX = (int) ev.getX();
            final int evY = (int) ev.getY();
            int nextImage = -1;

            ImageView imageView = (ImageView) v.findViewById(R.id.image);
            if (imageView == null)
                return false;

            Integer tagNum = (Integer) imageView.getTag();
            int currentResource = (tagNum == null) ? R.drawable.background_food_tracker : tagNum.intValue();

            switch (action) {

            case MotionEvent.ACTION_DOWN:

                if (currentResource == R.drawable.background_food_tracker) {

                    handledHere = true;

                } else
                    handledHere = true;
                break;

            case MotionEvent.ACTION_UP:

                int touchColor = getHotspotColor(R.id.image_areas, evX, evY);

                ColorTouchAreas ct = new ColorTouchAreas();
                int tolerance = 25;
                nextImage = R.drawable.background_food_tracker;

                if (ct.closeMatch(Color.RED, touchColor, tolerance))

                {

                    // GET INPUT EDIT INFORMATION ENTERED IN GRAMS
                    textInputRow1 = editRow1.getText().toString();

                    // VALIDATION NOT EMPTY FIELD EDITTEXT
                    if (textInputRow1.equals(""))

                    {
                        MainActivity.mpButtonSumit.start(); // sound

                        tToast("Please Enter Weight Of Grams For " + foodNameTempRow1);
                    }

                    else {

                        // SELECTS THE TYPE OF FOOD CATEGORY
                        switch (foodCategoryTempRow1) {

                        case "OILS":

                            // tToast("CLICK OILS ROW1"); // TESTING

                            for (int i = 0; i < oilsFoodInformation.length; i++) {

                                if (foodNameTempRow1.equals(oilsFoodInformation[i])) {

                                    MainActivity.mpButtonSumit.start(); // sound

                                    // tToast("STRING VALUE= " + textInputRow1);

                                    if (!"".equals(textInputRow1)) {

                                        gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);

                                        // tToast("INT VALUE= " +
                                        // String.valueOf(gramsEditTextInputParseRow1));
                                        // //TESTING

                                        resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
                                                * proteinInfoRule3Row1);
                                        resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1);
                                        // MAKE CALCULATION CARBS
                                        resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
                                        resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1);
                                        // MAKE CALCULATION FAT
                                        resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
                                        resultIntFatRow1 = (int) Math.round(resultIntFatRow1);
                                        // MAKE CALCULATION CALORIES
                                        resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
                                                * caloriesInfoRule3Row1);
                                        resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1);
                                        // PARSE BACK FROM INTEGER TO STRING TO SET
                                        // THE TEXT WHEN CLICK BUTTON IS CLICED
                                        textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
                                        textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
                                        textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
                                        textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);

                                        // CONCATENATE INFORMATION IN ROW 1
                                        concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
                                                + " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories

                                        ;

                                        // CREATE KEY ROW1
                                        keyRow1 = currentDateString + "-" + "keyRow1"; /
                                        sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

                                        // now get Editor
                                        SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();

                                        // put your value the key would be current
                                        // date + keyRow1
                                        editor.putString(keyRow1, concatenateInfoRow1);

                                        // commits your edits
                                        editor.commit();

                                    } // end if initial edittext is empty

                                    textViewProteinRow1.setText(textInputRow1ResultProtein);

                                    // CARBS GRAMS
                                    textViewCarbsRow1.setText(textInputRow1ResultCarbs);

                                    // FAT GRAMS
                                    textViewFatRow1.setText(textInputRow1ResultFat);

                                    // CALORIES GRAMS
                                    textViewCaloriesRow1.setText(textInputRow1ResultCalories);

                                } // end if Oils

                            } // end for Oils

                            break;

                        case "FRUITS":

                            for (int i = 0; i < fruitsFoodInformation.length; i++) {
                                if (foodNameTempRow1.equals(fruitsFoodInformation[i])) {

                                    MainActivity.mpButtonSumit.start(); // sound

                                    // tToast("STRING VALUE= " + textInputRow1);

                                    if (!"".equals(textInputRow1)) {

                                        gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);

                                        resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
                                                * proteinInfoRule3Row1);
                                        resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1); // ROUND
                                                                                // UP
                                                                                // VALUE

                                        // MAKE CALCULATION CARBS
                                        resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
                                        resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1); // ROUND

                                        resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
                                        resultIntFatRow1 = (int) Math.round(resultIntFatRow1); // ROUND

                                        resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
                                                * caloriesInfoRule3Row1);
                                        resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1); //
                                        textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
                                        textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
                                        textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
                                        textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);

                                        // CONCATENATE INFORMATION IN ROW 1
                                        concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
                                                + " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories

                                        ;

                                        // CREATE KEY ROW1
                                        keyRow1 = currentDateString + "-" + "keyRow1";

                                        sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

                                        // now get Editor
                                        SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();

                                        editor.putString(keyRow1, concatenateInfoRow1);

                                        // commits your edits
                                        editor.commit();

                                    } // end if initial edittext is empty

                                    // --------------------------------------------------------------------------

                                    textViewProteinRow1.setText(textInputRow1ResultProtein);

                                    textViewCarbsRow1.setText(textInputRow1ResultCarbs);

                                    textViewFatRow1.setText(textInputRow1ResultFat);

                                    textViewCaloriesRow1.setText(textInputRow1ResultCalories);

                                } // end if FRUITS

                            } // end for FRUITS

                            break;

                } // END HAND SUBMMIT RED IMAGE BUTTON

                else if (ct.closeMatch(Color.WHITE, touchColor, tolerance))
                    nextImage = R.drawable.background_food_tracker;
                ;
                if (currentResource == nextImage) {
                    nextImage = R.drawable.background_food_tracker;
                }
                handledHere = true;
                break;

            default:
                handledHere = false;
            } // end switch

            if (handledHere) {

                if (nextImage > 0) {
                    imageView.setImageResource(nextImage);
                    imageView.setTag(nextImage);
                }
            }
            return handledHere;
        }// end
                                                                                // Method

    public int getHotspotColor(int hotspotId, int x, int y) {

        ImageView img = (ImageView) findViewById(hotspotId);
        if (img == null) {
            // Log.d ("SubMain", "Hot spot image not found");
            return 0;
        } else {
            img.setDrawingCacheEnabled(true);
            Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
            if (hotspots == null) {
                // Log.d ("ImageAreasActivity", "Hot spot bitmap was not
                // created");
                return 0;
            } else {
                img.setDrawingCacheEnabled(false);
                return hotspots.getPixel(x, y);
            }
        }
    }// End Method

    // ----------------------------------------------------------------------
    public void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, s, duration);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    // ------------------------------------------------------------------------------------------------------------------
    public void onStart() {
                super.onStart();

                // GET INFORMATION BACK FROM SPINNER BASED ON POSITION STORED
                sharedPrefGetInfo = PreferenceManager.getDefaultSharedPreferences(this);

                int positionRow1 = sharedPrefGetInfo.getInt("ROW1", 0);

                // tToast(String.valueOf(positionRow1)); //TESTING

                if (positionRow1 >= 0) {
                    // LOAD SPINNER INFORMATION ROW1
                    spinnerFoodCategoryRow1.setSelection(positionRow1);

                }

 //---------------------------------------HERE IS THE PROBLEM SETTING THE CORRECT VALUE FOR SPINNER --------------------
      //THE SPINNER 2 IS NOT BEING SET
                Resources res = getResources();

                oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);

                if (spinnerFoodCategoryRow1.getSelectedItemPosition() == positionRow1) {
                    tToast("OILS TYPE TRUE");

                    int positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);

                    //THIS IS THE CORRECT POSITION FOR SPINNER 2
                    tToast("POSITION FOODNAME BACK = " + String.valueOf(positionRow1Oils));

                    // validation
                    if (positionRow1Oils >= 0) {

                        for (int n = 0; n < oilsFoodInformation.length; n++) {

                            spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                                    res.getStringArray(R.array.SpinnerArrayInfoOils));
                            spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);

                            tToast("Iteration # = " + n);
                            // LOAD SPINNER INFORMATION ROW1 OILS
                            if (n == positionRow1Oils) {

                                tToast("SPINNER FOOD NAME IS SET");
                                spinnerFoodNameRow1.setSelection(positionRow1Oils); // NOT
                                                                                // WORKING
                            }

                        }

                    } // end if

                }
                // -----------------------------------------------------------------------------------------------------------------------
                currentDateString = DateFormat.getDateInstance().format(new Date());

                keyRow1 = currentDateString + "-" + "keyRow1";
                getBackInformationRow1 = sharedPrefGetInfo.getString(keyRow1, "");

                // MAKE SURE THE ARRAY KEY IS NOT EMPTY
                if (!getBackInformationRow1.equals("")) {

                    getBackInformationParseRow1 = getBackInformationRow1.split(" - ", 4);

                    textViewProteinRow1.setText(getBackInformationParseRow1[0]);

                    textViewCarbsRow1.setText(getBackInformationParseRow1[1]);

                    textViewFatRow1.setText(getBackInformationParseRow1[2]);

                    textViewCaloriesRow1.setText(getBackInformationParseRow1[3]);

                }

        }// end class
```

答:
To fix my problem I just got the info stored (sharedPref) on onStart(); and set the spinner using the position (positionRow1Oils) gotten from it, on the method selection for spinner1  spinnerFoodNameRow1.setSelection(positionRow1Oils);

```<code>public void onStart() {
                super.onStart();

positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);
}

public String getSelectedFoodCategoryRow1() {

    Resources res = getResources();

    String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();

     sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

    //FOOD NAME OILS ROW1
    if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0)
    {

       //POPULATE INFORMATION FROM STRINGS XML TO FOOD NAME SPINNERS DEPENDING ON INFORMATION ON SELECTED ON FOOD CATEGORY SPINNER ROW1
        spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, res.getStringArray(R.array.SpinnerArrayInfoOils));
        spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);

        //PRESERVE SPINNER INFORMATION ROW1
         int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
         SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
         editor.putInt("ROW1", selectedPosition);
         editor.commit();

         *//SET SPINNER FOODNAME OILS WITH THE INFORMATION (POSITION) GOT FROM SHARERE PREFERENCE*
         spinnerFoodNameRow1.setSelection(positionRow1Oils);

        return selectedspinnerFoodCategoryRow1;
    }
</code>```

It seems that, when a spinner2 information is set based in spinner1 information, to preserve the information from spinner2 it should be set in spinner1 method and not on the onStart();

It hope it helps someone facing the same issue.

Body:
I have two spinners, the information on the 2nd spinner is based on the 1st spinner selection
EXAMPLE
SPINNER 1 PROTEIN DAIRY FRUITS
IF SPINNER 1 IS SET WITH PROTEIN then SPINNER 2 EGG CHICKEN
IF SPINNER 1 IS SET WITH FRUITS then SPINNER 2 APPLE ORANGE

Last value selected SPINNER 2 ORANGE

Now I want to preserve the last values selected of the SPINNER1 and SPINNER2, I am using SharedPreferences to accomplish this, it works as expected for SPINNER 1 FRUITS
Position 2 however for SPINNER2 it does not set the last value selected even though the position is correct position 1  when it is called onStart(); it selects the 1st value that is on the array APPLE

Any help would be appreciated

Thanks

public class TEST extends AppCompatActivity implements View.OnTouchListener {

    SharedPreferences sharedPrefStoreInfo, sharedPrefGetInfo;

    public String keyRow1, getBackInformationRow1;

    String concatenateInfoRow1, currentDateString, concatenateInfoTotals, getBackInformationTotals,
            getBackInformationParseTotals[],

            getBackInformationParseRow1[]

    ;

    // declare adaptors to bind with spinners
    ArrayAdapter<String> spinnerFoodCategoryRow1Adapter;

    // declare the references for the UI elements
    public static Spinner spinnerFoodCategoryRow1,

                spinnerFoodNameRow1,;

    private String[] oilsFoodInformation, fruitsFoodInformation, foodCategoryInformation;

    TextView day, date, textViewProteinRow1, textViewCarbsRow1, textViewFatRow1, textViewCaloriesRow1,

            textViewDailyTotalProtein, textViewDailyTotalCarbs, textViewDailyTotalFat, textViewDailyTotalCalories

    ;

    EditText editRow1;

    String textInputRow1, textInputRow1ResultProtein, textInputRow1ResultCarbs, textInputRow1ResultFat,
            textInputRow1ResultCalories,

            dailyTotalProtein, dailyTotalCarbs, dailyTotalFat, dailyTotalCalories

    ;

    int gramsEditTextInputParseRow1;

    double resultIntProteinRow1, resultIntCaloriesRow1, resultIntCarbsRow1, resultIntFatRow1,;

    double proteinInfoRule3Row1, carbsInfoRule3Row1, fatInfoRule3Row1, caloriesInfoRule3Row1,;

    public String foodNameTempRow1,;

    double canolaProtein = 0;
    double canolaCarbs = 0;
    double canolaFat = 1;
    double canolaCalories = 8.84;
    double coconutOilProtein = 0;
    double coconutOilCarbs = 0;
    double coconutOilFat = 1;
    double coconutOilCalories = 8.62;
    double cornProtein = 0;
    double cornCarbs = 0;
    double cornFat = 1;
    double cornCalories = 9;
    double applesProtein = 0;
    double applesCarbs = 0;
    double applesFat = 0;
    double applesCalories = 0;
    double apricotsProtein = 0;
    double apricotsCarbs = 0;
    double apricotsFat = 0;
    double apricotsCalories = 0;
    double bananasProtein = 0;
    double bananasCarbs = 0;
    double bananasFat = 0;
    double bananasCalories = 0;

    @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.food_tracker_layout); -
            editRow1 = (EditText) findViewById(R.id.editRow1);

            textViewProteinRow1 = (TextView) findViewById(R.id.textViewProteinR1);
            textViewCarbsRow1 = (TextView) findViewById(R.id.textViewCarbsR1);
            textViewFatRow1 = (TextView) findViewById(R.id.textViewFatR1);
            textViewCaloriesRow1 = (TextView) findViewById(R.id.textViewCaloriesR1);

            spinnerFoodCategoryRow1 = (Spinner) findViewById(R.id.spinner1R1);
            spinnerFoodNameRow1 = (Spinner) findViewById(R.id.spinner2R1);

            initializeSpinnerFoodCategoryAdapters();

            // CHANGE THE FONT SIZE OF SPINNER FOOD CATEGORY
            spinnerFoodCategoryRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    // Change the selected item's text color
                    ((TextView) view).setTextColor(Color.BLACK);
                    ((TextView) view).setTextSize(12);

                    getSelectedFoodCategoryRow1(); // **

                    // THIS IS TO CHANGE THE FONT SIZE OF SPINNER FOOD NAME
                    spinnerFoodNameRow1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            // Change the selected item's text color
                            ((TextView) view).setTextColor(Color.BLACK);
                            ((TextView) view).setTextSize(10);

                            getSelectedFoodNameRow1();

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });// end
                                        } // end

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });

        }// End Main

    public void initializeSpinnerFoodCategoryAdapters() {

        Resources res = getResources();

        spinnerFoodCategoryRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
        spinnerFoodCategoryRow1.setAdapter(spinnerFoodCategoryRow1Adapter);

        spinnerFoodCategoryRow2Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                res.getStringArray(R.array.SpinnerArrayInfoFoodCategory));
        spinnerFoodCategoryRow2.setAdapter(spinnerFoodCategoryRow2Adapter);

    }

    public String getSelectedFoodCategoryRow1() {

        Resources res = getResources();

        String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();

        sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

        // FOOD NAME OILS ROW1
        if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0) {

            spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                    res.getStringArray(R.array.SpinnerArrayInfoOils));
            spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);

            int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
            SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
            editor.putInt("ROW1", selectedPosition);
            editor.commit();

            return selectedspinnerFoodCategoryRow1;
        }

        if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 2) {

            spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                    res.getStringArray(R.array.SpinnerArrayInfoFruits));
            spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);
            int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
            SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
            editor.putInt("ROW1", selectedPosition);
            editor.commit();

            return selectedspinnerFoodCategoryRow1;
        }

        return selectedspinnerFoodCategoryRow1;

    }

    // RETRIEVE INFO FOODNAME FROM THE SPINNER ROW1
    public String getSelectedFoodNameRow1() {

        Resources res = getResources();

        String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();
        String selectedspinnerFoodNameRow1 = (String) spinnerFoodNameRow1.getSelectedItem();

        foodCategoryInformation = res.getStringArray(R.array.SpinnerArrayInfoFoodCategory);

        oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);
        fruitsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoFruits);

        for (int n = 0; n < foodCategoryInformation.length; n++) {

            // SELECTS INFORMATION ON THE FOOD CATEGORY SPINNER
            if (spinnerFoodCategoryRow1.getSelectedItemPosition() == n) {

                // SELECT TYPE OF FOOD CATEGORY
                switch (selectedspinnerFoodCategoryRow1) {

                case "OILS":

                    foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;

                    // ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN OILS
                    for (int i = 0; i < oilsFoodInformation.length; i++) {

                        // SELECT FOOD NAME BASED ON POSITION IN DAIRY
                        if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {

                            SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
                            editor.putInt("ROW1-OILS", i);
                            editor.commit();
                            if (selectedspinnerFoodNameRow1.equals("Canola")) {

                                // ASSIGN THE FOOD NAME SELECTED TO A
                                // foodNameTempRow1 VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                // ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
                                // THE CALCULATION CLICK BUTTON
                                proteinInfoRule3Row1 = canolaProtein;
                                carbsInfoRule3Row1 = canolaCarbs;
                                fatInfoRule3Row1 = canolaFat;
                                caloriesInfoRule3Row1 = canolaCalories;

                            } // end IF CANOLA

                            if (selectedspinnerFoodNameRow1.equals("Coconut Oil")) {

                                // ASSIGN THE FOOD NAME SELECTED TO A
                                // foodNameTempRow1 VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = coconutOilProtein;
                                carbsInfoRule3Row1 = coconutOilCarbs;
                                fatInfoRule3Row1 = coconutOilFat;
                                caloriesInfoRule3Row1 = coconutOilCalories;

                            } // end IF Coconut Oil

                            if (selectedspinnerFoodNameRow1.equals("Corn")) {

                                // ASSIGN THE FOOD NAME SELECTED TO A
                                // foodNameTempRow1 VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = cornProtein;
                                carbsInfoRule3Row1 = cornCarbs;
                                fatInfoRule3Row1 = cornFat;
                                caloriesInfoRule3Row1 = cornCalories;

                            } // end IF Corn

                        } // end if OILS POSITION

                    } // end for OILS

                    break;

                case "FRUITS":

                    // ASSIGN THE FOOD CATEGORY SELECTED TO A
                    // foodCategoryTempRow1 VARIABLE
                    foodCategoryTempRow1 = selectedspinnerFoodCategoryRow1;

                    // ITERATE THE ARRAY TO SELECT THE FOOD NAME ITEM IN DAIRY
                    for (int i = 0; i < fruitsFoodInformation.length; i++) {

                        // SELECT FOOD NAME BASED ON POSITION IN DAIRY
                        if (spinnerFoodNameRow1.getSelectedItemPosition() == i) {

                            if (selectedspinnerFoodNameRow1.equals("Apples")) {
                                // ASSIGN THE FOOD SELECTED TO A
                                // foodNameTempRow1Dairy VARIABLE
                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                // ASSIGN INFO TO VARIABLES THAT WILL BE USED ON
                                // THE CALCULATION CLICK BUTTON
                                proteinInfoRule3Row1 = applesProtein;
                                carbsInfoRule3Row1 = applesCarbs;
                                fatInfoRule3Row1 = applesFat;
                                caloriesInfoRule3Row1 = applesCalories;

                            } // end if Apples

                            if (selectedspinnerFoodNameRow1.equals("Apricots")) {

                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = apricotsProtein;
                                carbsInfoRule3Row1 = apricotsCarbs;
                                fatInfoRule3Row1 = apricotsFat;
                                caloriesInfoRule3Row1 = apricotsCalories;

                            } // end if Apricots

                            if (selectedspinnerFoodNameRow1.equals("Bananas")) {

                                foodNameTempRow1 = selectedspinnerFoodNameRow1;

                                proteinInfoRule3Row1 = bananasProtein;
                                carbsInfoRule3Row1 = bananasCarbs;
                                fatInfoRule3Row1 = bananasFat;
                                caloriesInfoRule3Row1 = bananasCalories;

                            } // end if Bananas

                        } // end if FRUITS POSITION
                    } // end for FRUITS

                    break;

                }// END SWITCH
            } // IF OUTER

        } // OUTER FOR LOOP

        return selectedspinnerFoodNameRow1;

    }// end METHOD GET FOODNAME ROW1

    public boolean onTouch(View v, MotionEvent ev) {
            boolean handledHere = false;

            final int action = ev.getAction();

            final int evX = (int) ev.getX();
            final int evY = (int) ev.getY();
            int nextImage = -1;

            ImageView imageView = (ImageView) v.findViewById(R.id.image);
            if (imageView == null)
                return false;

            Integer tagNum = (Integer) imageView.getTag();
            int currentResource = (tagNum == null) ? R.drawable.background_food_tracker : tagNum.intValue();

            switch (action) {

            case MotionEvent.ACTION_DOWN:

                if (currentResource == R.drawable.background_food_tracker) {

                    handledHere = true;

                } else
                    handledHere = true;
                break;

            case MotionEvent.ACTION_UP:

                int touchColor = getHotspotColor(R.id.image_areas, evX, evY);

                ColorTouchAreas ct = new ColorTouchAreas();
                int tolerance = 25;
                nextImage = R.drawable.background_food_tracker;

                if (ct.closeMatch(Color.RED, touchColor, tolerance))

                {

                    // GET INPUT EDIT INFORMATION ENTERED IN GRAMS
                    textInputRow1 = editRow1.getText().toString();

                    // VALIDATION NOT EMPTY FIELD EDITTEXT
                    if (textInputRow1.equals(""))

                    {
                        MainActivity.mpButtonSumit.start(); // sound

                        tToast("Please Enter Weight Of Grams For " + foodNameTempRow1);
                    }

                    else {

                        // SELECTS THE TYPE OF FOOD CATEGORY
                        switch (foodCategoryTempRow1) {

                        case "OILS":

                            // tToast("CLICK OILS ROW1"); // TESTING

                            for (int i = 0; i < oilsFoodInformation.length; i++) {

                                if (foodNameTempRow1.equals(oilsFoodInformation[i])) {

                                    MainActivity.mpButtonSumit.start(); // sound

                                    // tToast("STRING VALUE= " + textInputRow1);

                                    if (!"".equals(textInputRow1)) {

                                        gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);

                                        // tToast("INT VALUE= " +
                                        // String.valueOf(gramsEditTextInputParseRow1));
                                        // //TESTING

                                        resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
                                                * proteinInfoRule3Row1);
                                        resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1);
                                        // MAKE CALCULATION CARBS
                                        resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
                                        resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1);
                                        // MAKE CALCULATION FAT
                                        resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
                                        resultIntFatRow1 = (int) Math.round(resultIntFatRow1);
                                        // MAKE CALCULATION CALORIES
                                        resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
                                                * caloriesInfoRule3Row1);
                                        resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1);
                                        // PARSE BACK FROM INTEGER TO STRING TO SET
                                        // THE TEXT WHEN CLICK BUTTON IS CLICED
                                        textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
                                        textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
                                        textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
                                        textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);

                                        // CONCATENATE INFORMATION IN ROW 1
                                        concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
                                                + " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories

                                        ;

                                        // CREATE KEY ROW1
                                        keyRow1 = currentDateString + "-" + "keyRow1"; /
                                        sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

                                        // now get Editor
                                        SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();

                                        // put your value the key would be current
                                        // date + keyRow1
                                        editor.putString(keyRow1, concatenateInfoRow1);

                                        // commits your edits
                                        editor.commit();

                                    } // end if initial edittext is empty

                                    textViewProteinRow1.setText(textInputRow1ResultProtein);

                                    // CARBS GRAMS
                                    textViewCarbsRow1.setText(textInputRow1ResultCarbs);

                                    // FAT GRAMS
                                    textViewFatRow1.setText(textInputRow1ResultFat);

                                    // CALORIES GRAMS
                                    textViewCaloriesRow1.setText(textInputRow1ResultCalories);

                                } // end if Oils

                            } // end for Oils

                            break;

                        case "FRUITS":

                            for (int i = 0; i < fruitsFoodInformation.length; i++) {
                                if (foodNameTempRow1.equals(fruitsFoodInformation[i])) {

                                    MainActivity.mpButtonSumit.start(); // sound

                                    // tToast("STRING VALUE= " + textInputRow1);

                                    if (!"".equals(textInputRow1)) {

                                        gramsEditTextInputParseRow1 = Integer.parseInt(textInputRow1);

                                        resultIntProteinRow1 = (double) (gramsEditTextInputParseRow1
                                                * proteinInfoRule3Row1);
                                        resultIntProteinRow1 = (int) Math.round(resultIntProteinRow1); // ROUND
                                                                                // UP
                                                                                // VALUE

                                        // MAKE CALCULATION CARBS
                                        resultIntCarbsRow1 = (double) (gramsEditTextInputParseRow1 * carbsInfoRule3Row1);
                                        resultIntCarbsRow1 = (int) Math.round(resultIntCarbsRow1); // ROUND

                                        resultIntFatRow1 = (double) (gramsEditTextInputParseRow1 * fatInfoRule3Row1);
                                        resultIntFatRow1 = (int) Math.round(resultIntFatRow1); // ROUND

                                        resultIntCaloriesRow1 = (double) (gramsEditTextInputParseRow1
                                                * caloriesInfoRule3Row1);
                                        resultIntCaloriesRow1 = (int) Math.round(resultIntCaloriesRow1); //
                                        textInputRow1ResultProtein = Integer.toString((int) resultIntProteinRow1);
                                        textInputRow1ResultCarbs = Integer.toString((int) resultIntCarbsRow1);
                                        textInputRow1ResultFat = Integer.toString((int) resultIntFatRow1);
                                        textInputRow1ResultCalories = Integer.toString((int) resultIntCaloriesRow1);

                                        // CONCATENATE INFORMATION IN ROW 1
                                        concatenateInfoRow1 = textInputRow1ResultProtein + " - " + textInputRow1ResultCarbs
                                                + " - " + textInputRow1ResultFat + " - " + textInputRow1ResultCalories

                                        ;

                                        // CREATE KEY ROW1
                                        keyRow1 = currentDateString + "-" + "keyRow1";

                                        sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

                                        // now get Editor
                                        SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();

                                        editor.putString(keyRow1, concatenateInfoRow1);

                                        // commits your edits
                                        editor.commit();

                                    } // end if initial edittext is empty

                                    // --------------------------------------------------------------------------

                                    textViewProteinRow1.setText(textInputRow1ResultProtein);

                                    textViewCarbsRow1.setText(textInputRow1ResultCarbs);

                                    textViewFatRow1.setText(textInputRow1ResultFat);

                                    textViewCaloriesRow1.setText(textInputRow1ResultCalories);

                                } // end if FRUITS

                            } // end for FRUITS

                            break;

                } // END HAND SUBMMIT RED IMAGE BUTTON

                else if (ct.closeMatch(Color.WHITE, touchColor, tolerance))
                    nextImage = R.drawable.background_food_tracker;
                ;
                if (currentResource == nextImage) {
                    nextImage = R.drawable.background_food_tracker;
                }
                handledHere = true;
                break;

            default:
                handledHere = false;
            } // end switch

            if (handledHere) {

                if (nextImage > 0) {
                    imageView.setImageResource(nextImage);
                    imageView.setTag(nextImage);
                }
            }
            return handledHere;
        }// end
                                                                                // Method

    public int getHotspotColor(int hotspotId, int x, int y) {

        ImageView img = (ImageView) findViewById(hotspotId);
        if (img == null) {
            // Log.d ("SubMain", "Hot spot image not found");
            return 0;
        } else {
            img.setDrawingCacheEnabled(true);
            Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
            if (hotspots == null) {
                // Log.d ("ImageAreasActivity", "Hot spot bitmap was not
                // created");
                return 0;
            } else {
                img.setDrawingCacheEnabled(false);
                return hotspots.getPixel(x, y);
            }
        }
    }// End Method

    // ----------------------------------------------------------------------
    public void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, s, duration);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    // ------------------------------------------------------------------------------------------------------------------
    public void onStart() {
                super.onStart();

                // GET INFORMATION BACK FROM SPINNER BASED ON POSITION STORED
                sharedPrefGetInfo = PreferenceManager.getDefaultSharedPreferences(this);

                int positionRow1 = sharedPrefGetInfo.getInt("ROW1", 0);

                // tToast(String.valueOf(positionRow1)); //TESTING

                if (positionRow1 >= 0) {
                    // LOAD SPINNER INFORMATION ROW1
                    spinnerFoodCategoryRow1.setSelection(positionRow1);

                }

 //---------------------------------------HERE IS THE PROBLEM SETTING THE CORRECT VALUE FOR SPINNER --------------------
      //THE SPINNER 2 IS NOT BEING SET
                Resources res = getResources();

                oilsFoodInformation = res.getStringArray(R.array.SpinnerArrayInfoOils);

                if (spinnerFoodCategoryRow1.getSelectedItemPosition() == positionRow1) {
                    tToast("OILS TYPE TRUE");

                    int positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);

                    //THIS IS THE CORRECT POSITION FOR SPINNER 2
                    tToast("POSITION FOODNAME BACK = " + String.valueOf(positionRow1Oils));

                    // validation
                    if (positionRow1Oils >= 0) {

                        for (int n = 0; n < oilsFoodInformation.length; n++) {

                            spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                                    res.getStringArray(R.array.SpinnerArrayInfoOils));
                            spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);

                            tToast("Iteration # = " + n);
                            // LOAD SPINNER INFORMATION ROW1 OILS
                            if (n == positionRow1Oils) {

                                tToast("SPINNER FOOD NAME IS SET");
                                spinnerFoodNameRow1.setSelection(positionRow1Oils); // NOT
                                                                                // WORKING
                            }

                        }

                    } // end if

                }
                // -----------------------------------------------------------------------------------------------------------------------
                currentDateString = DateFormat.getDateInstance().format(new Date());

                keyRow1 = currentDateString + "-" + "keyRow1";
                getBackInformationRow1 = sharedPrefGetInfo.getString(keyRow1, "");

                // MAKE SURE THE ARRAY KEY IS NOT EMPTY
                if (!getBackInformationRow1.equals("")) {

                    getBackInformationParseRow1 = getBackInformationRow1.split(" - ", 4);

                    textViewProteinRow1.setText(getBackInformationParseRow1[0]);

                    textViewCarbsRow1.setText(getBackInformationParseRow1[1]);

                    textViewFatRow1.setText(getBackInformationParseRow1[2]);

                    textViewCaloriesRow1.setText(getBackInformationParseRow1[3]);

                }

        }// end class

Body:
To fix my problem I just got the info stored (sharedPref) on onStart(); and set the spinner using the position (positionRow1Oils) gotten from it, on the method selection for spinner1  spinnerFoodNameRow1.setSelection(positionRow1Oils);

public void onStart() {
                super.onStart();

positionRow1Oils = sharedPrefGetInfo.getInt("ROW1-OILS", 0);
}

public String getSelectedFoodCategoryRow1() {

    Resources res = getResources();

    String selectedspinnerFoodCategoryRow1 = (String) spinnerFoodCategoryRow1.getSelectedItem();

     sharedPrefStoreInfo = PreferenceManager.getDefaultSharedPreferences(this);

    //FOOD NAME OILS ROW1
    if (spinnerFoodCategoryRow1.getSelectedItemPosition() == 0)
    {

       //POPULATE INFORMATION FROM STRINGS XML TO FOOD NAME SPINNERS DEPENDING ON INFORMATION ON SELECTED ON FOOD CATEGORY SPINNER ROW1
        spinnerFoodNameRow1Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, res.getStringArray(R.array.SpinnerArrayInfoOils));
        spinnerFoodNameRow1.setAdapter(spinnerFoodNameRow1Adapter);

        //PRESERVE SPINNER INFORMATION ROW1
         int selectedPosition = spinnerFoodCategoryRow1.getSelectedItemPosition();
         SharedPreferences.Editor editor = sharedPrefStoreInfo.edit();
         editor.putInt("ROW1", selectedPosition);
         editor.commit();

         *//SET SPINNER FOODNAME OILS WITH THE INFORMATION (POSITION) GOT FROM SHARERE PREFERENCE*
         spinnerFoodNameRow1.setSelection(positionRow1Oils);

        return selectedspinnerFoodCategoryRow1;
    }

It seems that, when a spinner2 information is set based in spinner1 information, to preserve the information from spinner2 it should be set in spinner1 method and not on the onStart();

It hope it helps someone facing the same issue.


问:
What is a good design for an interface with optional components?
Suppose I have an interface that supports a few potential operations:

```<code>interface Frobnicator {
    int doFoo(double v);
    int doBar();
}
</code>```

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

```<code>interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}
</code>```

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

答:
I see a few ways of handling this. One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException. This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

As you said, the general tactic is to use the template method design pattern. An excellent example is the HttpServlet.

Here's how you could achieve the same.

```<code>public interface Frobnicator {
    int doFoo(double v);
    int doBar();
}
</code>```

```<code>public abstract class BaseFrobnicator implements Frobnicator {
    public int doFoo(double v) {
        throw new UnsupportedOperationException();
    }
    public int doBar() {
        throw new UnsupportedOperationException();
    }
}
</code>```

```<code>/**
 * This concrete frobnicator only supports the {@link #doBar()} method.
 */
public class ConcreteFrobnicator extends BaseFrobnicator {
    public int doBar() {
        return 42;
    }
}
</code>```

The client has just to read the docs and handle the UnsupportedOperationException accordingly. Since it's a RuntimeException, it's a perfect case for a "programmer error". True, it's not fail-fast (i.e. not compiletime), but that's what you get paid for as developer. Just prevent it or catch and handle it.

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have an interface that supports a few potential operations:

interface Frobnicator {
    int doFoo(double v);
    int doBar();
}

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

Body:
I see a few ways of handling this. One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException. This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

As you said, the general tactic is to use the template method design pattern. An excellent example is the HttpServlet.

Here's how you could achieve the same.

public interface Frobnicator {
    int doFoo(double v);
    int doBar();
}

public abstract class BaseFrobnicator implements Frobnicator {
    public int doFoo(double v) {
        throw new UnsupportedOperationException();
    }
    public int doBar() {
        throw new UnsupportedOperationException();
    }
}

/**
 * This concrete frobnicator only supports the {@link #doBar()} method.
 */
public class ConcreteFrobnicator extends BaseFrobnicator {
    public int doBar() {
        return 42;
    }
}

The client has just to read the docs and handle the UnsupportedOperationException accordingly. Since it's a RuntimeException, it's a perfect case for a "programmer error". True, it's not fail-fast (i.e. not compiletime), but that's what you get paid for as developer. Just prevent it or catch and handle it.


问:
Google Map : how to get the city + zipcode + state + country in a multiselect input
I use the following example from Google map documentation, but I would like to get the zipcode when I search for a city.
For instance, if I type New York, NY, United States I get all the needed info except the zip code, is there a chance to get this information too? The aim is to have a multiselect input and have the possibility to create a list of cities with Google Autosuggest API.</p>

答:
two years after but I was facing the same issue and
I've found in this post that it's not possible to do that with google maps v3 API

Google Map V3 Postal Code not returned

that:

"The Google Maps API geocoding service will only return a zip code if you give it a street address. Giving just the City and State won't return a zip code, most likely because there are usually multiple zipcodes per city (in the US at least)". which makes sens because unless you're totally sure of the location in the city it's not really possible to guess the correct zip code...


问:
Python, lxml and removing outer tag from using lxml.html.tostring(el)
I am using the below to get all of the html content of a section to save to a database

```<code>el = doc.get_element_by_id('productDescription')
lxml.html.tostring(el)
</code>```

The product description has a tag that looks like this:

```<code><div id='productDescription'>

     <THE HTML CODE I WANT>

</div>
</code>```

The code works great , gives me all of the html code but how do I remove the outer layer i.e. the
 and the closing tag
 ?

答:
Use regexp.</p>

```<code>def strip_outer_tag(html_fragment):
    import re
    outer_tag = re.compile(r'^<[^>]+>(.*?)</[^>]+>$', re.DOTALL)
    return outer_tag.search(html_fragment).group(1)

html_fragment = strip_outer_tag(tostring(el, encoding='unicode'))  # `encoding` is optionaly
</code>```

Body:
I am using the below to get all of the html content of a section to save to a database

el = doc.get_element_by_id('productDescription')
lxml.html.tostring(el)

The product description has a tag that looks like this:

     <THE HTML CODE I WANT>

The code works great , gives me all of the html code but how do I remove the outer layer i.e. the
 and the closing tag
 ?

Body:
Use regexp.

def strip_outer_tag(html_fragment):
    import re
    outer_tag = re.compile(r'^<[^>]+>(.*?)</[^>]+>$', re.DOTALL)
    return outer_tag.search(html_fragment).group(1)

html_fragment = strip_outer_tag(tostring(el, encoding='unicode'))  # `encoding` is optionaly