0

I am currently trying to just get the selected value from the spinner, save that, then when the instance is restored (after the app is closed) the value will be inserted into a TextView I dragged onto the layout.

Anyways, Below is the code I have so far

 TextView example;
    private String someVarB;
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        String values = spinner.getSelectedItem().toString(); //gets the values from the spinner to the variable values

        outState.putString(values, someVarB); //saves the v alues to the variable someVarB, which will be called when restored.
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        someVarB = savedInstanceState.getString("someVarB");
        example.setTextSize(someVarB);
        //try setting the variable to an textview which you will put on manually on the xml.
    }

However I face a problem.

'cannot resolve symbol spinner'. spinner is the variable name of the spinners created in my code, which are created in a private method. What would I do so I can call this spinner variable anywhere else in my code?

FAB CODE

floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();
                spinner = findViewById(R.id.spinner);



                // Handle ze click.
                final Spinner spinner = makeSpinner();
                mLinearLayout.addView(spinner);


                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) spinner.getLayoutParams();
                layoutParams.setMargins(5, 100, 10, 0); //top 70

                Resources resources = getResources();
                DisplayMetrics metrics = resources.getDisplayMetrics();

                layoutParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
                layoutParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
                spinner.setLayoutParams(layoutParams);

                final View newView = makeView();
                //Add a new view
                mLinearLayout.addView(newView);
                mViews.add(newView);


                final EditText newEdittext = makeEdittext();
                mLinearLayout.addView(newEdittext);
                mEdittexts.add(newEdittext);


                final int listSize = mViews.size();


                //code for deleting the said item.
                newView.setOnClickListener(new View.OnClickListener() {
                    //start
                    @Override
                    public void onClick(View view) {

                        //when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.

                        final View.OnClickListener context = this;


                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create.this);


                        // set title
                        alertDialogBuilder.setTitle("Delete Item");

                        // set dialog message
                        alertDialogBuilder
                                .setMessage("Are you sure you want to delete this item?")
                                .setCancelable(false)
                                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // if this button is clicked, close
                                        // current activity


                                        if (listSize > 0) {

                                            mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
                                            mSpinners.get(listSize - 1).setVisibility(View.GONE);
                                            mViews.get(listSize - 1).setVisibility(View.GONE);
                                            mTextviews.get(listSize - 1).setVisibility(View.GONE);
                                            mEdittexts.get(listSize - 1).setVisibility(View.GONE);
                                            Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();

                                        }


                                    }
                                })
                                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // if this button is clicked, just close
                                        // the dialog box and do nothing
                                        dialog.cancel();
                                    }
                                });

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();


                    }
                });


                //Add a new checkbox
                final CheckBox newCheckbox = makeCheckbox();
                mLinearLayout.addView(newCheckbox);

                //TODO add checkbox to your list
                mCheckboxes.add(newCheckbox);


                final TextView newTextview = makeTextview();
                mLinearLayout.addView(newTextview);
                mTextviews.add(newTextview);

                //TODO Add the spinner on item selected listener to get selected items
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                        String currentItem = itemList.get(position);
                        String aisleNumber = numberItemValues.get(currentItem);
                        //TODO you can use the above aisle number to add to your text view
                        //mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
                        newTextview.setText(aisleNumber);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parentView) {
                        //  code here
                    }

                });


            }
        });
  • If you want to preserve state across things like app restarts, I think you should be using either shared preferences or some sort of local/remote database, e.g. SQLite. – Tim Biegeleisen Sep 03 '18 at 02:42

1 Answers1

0

Solution:

If you're getting an error like "cannot resolve symbol spinner" ... You must declare and initialize it like below:

private Spinner spinner;

as Global Variable then: in your onCreate (),

spinner = findViewById(R.id.your_spinner_id);

In onCreate().

Hope it helps.

Ümañg ßürmån
  • 8,143
  • 4
  • 21
  • 40
  • Hi, makes sense. however, how do I know what the id of my spinner is? because these spinners aren't in my xml, I'm actually programatically creating them when I press the FAB button. –  Sep 03 '18 at 03:12
  • You need to set id programmatically.. In your values folder create an xml called `ids.xml` then make an id item and call it spinner. Then in your FAB, spinner.setId(R.id.whatever_id_you_give); then if will work. In addition, please post your FAB code – Ümañg ßürmån Sep 03 '18 at 03:21
  • @Magic_Whizz Was it helpful.? – Ümañg ßürmån Sep 03 '18 at 05:21
  • hi, Im just trying to run my app right now. I already had an ids.xml so I added what you said in. also just putting my fab code in the post right now. hope it works –  Sep 03 '18 at 05:22
  • I'm marking your answer complete because it makes sense and it is correct however I think I need to use a different way to save instance states in my situation because I have multiple spinners and it's a bit confusing. thanks though –  Sep 03 '18 at 05:29
  • (it's this question here https://stackoverflow.com/questions/51834790/taking-the-state-of-one-activity-to-another which I am confused on but thanks for telling me how to make variables global because I didn't know that!) –  Sep 03 '18 at 05:30
  • 1
    Thanks, But you don't have to use instance states now. Have you heard about the new architectural patters from android? – Ümañg ßürmån Sep 03 '18 at 05:30
  • I haven't...what is that? –  Sep 03 '18 at 05:30
  • It has a class called ViewModel which constrols your instance state when the device is rotated. – Ümañg ßürmån Sep 03 '18 at 05:31
  • I am trying to save the instance state of spinners, ; - like, when the user presses the FAB, a spinner checkbox edittext appear, then when you press the fab again, those elements appear again. so Im trying to save the instance state of when you add many of those set elements and save the instance state of when you select values from the spinners too. when you close and reopen the app they show –  Sep 03 '18 at 05:32
  • I am not really interested in saving the instance state for when device is rotated. I have disabled my app so it cant go landscape, it is only portrait :) –  Sep 03 '18 at 05:32
  • Oh :) You can use SharedPreferences instead. It's much easier to use. – Ümañg ßürmån Sep 03 '18 at 05:34
  • yes, I am having a read of that now. thank you so much for your help btw :D –  Sep 03 '18 at 05:34
  • hi sorry this is off topic to the post but I was looking at shared preferences on the android google doc, and found this bit of code and put it in my code but it says Cant resolve method getActivity()? –  Sep 03 '18 at 05:45
  • `SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);` –  Sep 03 '18 at 05:45
  • 1
    https://stackoverflow.com/questions/23024831/android-shared-preferences-example Check out this accepted answer.. I always refer this for any of my projects. – Ümañg ßürmån Sep 03 '18 at 05:48