4

I have two activity screens: Create and View. Create is where the user creates their shopping list. View is where they view their list (and can still add items).

UPDATE: Some may say why not just use the one activity instead of having both activities the same basically but this is how I've planned it out. I want it so when you add spinners by pressing the FAB on the create screen, you can select values from those. Then when you go back to the main menu, then to the view screen, those spinners and the selected values from the create screen appear here too. Additionally I want it so when you close the app and reopen it, all the spinners and values that you selected still appear. If there are any questions please comment.

I do appreciate the posts below with the examples however I'm just confused as to if it fits my situation or not!

Below is my create.java code. (view.java has exactly the same code just with .view in places instead of .create, and some extra code.)

create.java

public class create extends AppCompatActivity {


    private LinearLayout mLinearLayout;
    private ArrayList<SearchableSpinner> mSpinners;
    private List<AppCompatButton> mButtons = new ArrayList<>();
    private List<CheckBox> mCheckboxes = new ArrayList<>();
    private List<TextView> mTextviews = new ArrayList<>();
    private List<EditText> mEdittexts = new ArrayList<>();
    private List<View> mViews = new ArrayList<>();
    private Map<String, String> numberItemValues = new HashMap<>();
    List<String> itemList = new ArrayList<>();
    //Button buttontest;
    // TextView textview;
    // CheckBox checkbox;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        GlobalClass globalClass = (GlobalClass) this.getApplicationContext();


        ArrayList<String> items = new ArrayList<>();
        items.add(String.valueOf(mSpinners)); // add you selected item
        globalClass.setItems(items);


        mSpinners = new ArrayList<>();

        mLinearLayout = findViewById(R.id.my_linearLayout);


        //code for the add button to add more items
        FloatingActionButton floatingActionButton =
                (FloatingActionButton) findViewById(R.id.fab);

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


                // 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
                    }

                });


            }
        });

    }










   /* //creates the 3 buttons on the side.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.create_menu, menu);
        return true;
    }
*/





    //use a relative layout and specify which ones are to layout_toRightOf and layout_below

    //DUPLICATING ITEMS WHEN FAB IS PRESSED//
    private CheckBox makeCheckbox() {
        //Create new Checkbox
        CheckBox checkbox = new CheckBox(this);

        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);


        //setup relative layout for the positioning of the objects

       /* RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
                relativeParams.addRule(RelativeLayout.RIGHT_OF, textview); //can't  resolve symbol textview
                )

        checkbox.setLayoutParams(relativeParams);*/
        checkbox.setLayoutParams(layoutParams);
        return checkbox;
    }


    private TextView makeTextview() {
        //create new textview
        TextView textview = new TextView(this);

        //setup layout

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        textview.setLayoutParams(layoutParams);
        textview.setText("ihi");


        return textview;
    }


    private EditText makeEdittext() {
        //create new edittext
        EditText edittext = new EditText(this);

        //setup layout
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(50, 50); // Width , height
        edittext.setLayoutParams(lparams);
        edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);

        return edittext;

    }




    private View makeView() {
        //create new View

        View view = new View(this);
        view.setBackgroundColor(Color.parseColor("#ffffff"));
        LinearLayout.LayoutParams layoutParams =  new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100);
        new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);
        //LinearLayout.LayoutParams.MATCH_PARENT,
        // LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setClickable(true);




        view.setLayoutParams(layoutParams);


        //setup layout

        return view;


    }






    private Spinner makeSpinner() {
        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
        CSVFile csvFile = new CSVFile(inputStream);
        //TODO I made this variable global, declared it at the very top of this file
        itemList = csvFile.read();

        //Create new spinner
        // SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);
        SearchableSpinner spinner = new SearchableSpinner(this);


        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        spinner.setLayoutParams(layoutParams);
        MyListAdapter adapter = new MyListAdapter(this, R.layout.listrow, R.id.txtid, itemList);


        spinner.setAdapter(adapter);



        //Add it to your list of spinners so you can retrieve their data when you click the getSpinner button
        mSpinners.add(spinner);
        return spinner;
    }



    private class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public List<String> read() {

            List<String> resultList = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] row = line.split(",");
                    //TODO I edited this part so that you'd add the values in our new hash map variable
                    numberItemValues.put(row[1], row[0]);
                    resultList.add(row[1]);
                }
            } catch (IOException e) {
                Log.e("Main", e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("Main", e.getMessage());
                }
            }
            return resultList;
        }
    }}

create xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground"
    android:minHeight="170dp"
    tools:context=".create"
    tools:layout_editor_absoluteY="81dp">


    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView2"
        android:layout_width="match_parent"
        android:layout_height="438dp"
        android:fillViewport="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="0dp">


        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/my_linearLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">


        </LinearLayout>


    </ScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="60dp"
        android:layout_height="70dp"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="8dp"
        android:src="@android:drawable/ic_input_add"
        app:backgroundTint="@color/colorCreate"
        app:elevation="6dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:pressedTranslationZ="12dp"
        android:tint="@color/colorBackground"/>


    <View
        android:id="@+id/subheading"
        android:layout_width="match_parent"
        android:layout_height="83dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="1dp"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"
        android:layout_marginStart="1dp"
        android:layout_marginTop="2dp"
        android:background="@color/colorBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        />

    <TextView
        android:id="@+id/example"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="492dp"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        android:hint="test"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view"
        android:layout_width="320dp"
        android:layout_height="1dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="76dp"
        android:background="@color/colorText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/view2"
        android:layout_width="320dp"
        android:layout_height="1dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="28dp"
        android:background="@color/colorText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"

        android:layout_marginTop="12dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/done_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/view2" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="128dp"
        android:layout_marginRight="128dp"
        android:layout_marginTop="8dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/aisle_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/view"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view2"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginTop="5dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/qty_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/view"
        app:layout_constraintEnd_toStartOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/view2"
        app:layout_constraintVertical_bias="0.7" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="@font/droid_sans"
        android:text="@string/item_label"
        android:textColor="@color/colorText"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/view"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view2"
        app:layout_constraintVertical_bias="1.0" />


</android.support.constraint.ConstraintLayout>
Rob
  • 26,989
  • 16
  • 82
  • 98
  • 1
    Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/178789/discussion-on-question-by-magic-whizz-taking-the-state-of-one-activity-to-anothe). – Samuel Liew Aug 26 '18 at 09:34

9 Answers9

5

[UPDATED]

So basically, you have 2 activity classes, create and view (as you mentioned).

Declare your spinner in the form of global. All other explanation of the code is in the form of comment.

public class create extends AppCompatActivity {

private LinearLayout mLinearLayout;
private ArrayList<SearchableSpinner> mSpinners;
//TODO add the below list of buttons and checkboxes
//private List<AppCompatButton> mButtons = new ArrayList<>();
private List<CheckBox> mCheckboxes = new ArrayList<>();
private List<View> mViews = new ArrayList<>();

Button buttonGo;

//define spinner here
Spinner spinner;


//your own code
......
floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();

            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            // Handle the click.


            //initialise your spinner here
            spinner = makeSpinner();

            //your code as usual
        }

    //put this some where in your code where you want to start another activity after your operations are done (usually in onClick of something)
    {
        Intent i= new Intent(this, YourSecondClass.class);
        //Create the bundle
        Bundle bundle = new Bundle();

        //Add your data to bundle one by one, in this case passing spinner selected value, 
        //replace val1 with your own variable name
        bundle.putString("val1", spinner.getSelectedItem().toString());

        //if you have more spinner,add in similar way
        bundle.putString("val2", spinner2.getSelectedItem().toString());

        //Add the bundle to the intent
        i.putExtras(bundle);
        startActivity(i);
    }


}
}

Here is the sample for view activity.

public class view extends AppCompatActivity {

...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        //initialise your spinner here
        spinner = makeSpinner();

        //Get bundle from previous intent(activity)
        Bundle bundle = getIntent().getExtras();

        //Extract the data…
        String val1= bundle.getString("val1");
        String val2= bundle.getString("val2");

        //USUALLY, you will have a list of items in your spinner, do what you should do, this is just an example.
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //set the adapter
        mSpinner.setAdapter(adapter);


        if (val1 != null) {
            int spinnerPosition = adapter.getPosition(val1);
            spinner.setSelection(spinnerPosition);
        }       
        ...


    }
...

}

NOTE: This is just a guidance or 'framework' to give you some clues on where you should place your code. NOT FULL SOLUTION as your code is too long and I can't assure its correct, so I did not include them.

Angus
  • 3,680
  • 1
  • 12
  • 27
  • when you say 'before you start another activity' do you mean at the start of my create activity? –  Aug 14 '18 at 06:53
  • 2
    I mean in your first activity, when you start your second activity, you can use bundle to pass value – Angus Aug 14 '18 at 06:56
  • would this still work because In my situation I am programming it to duplicate these spinners instead of me putting them in my xml. –  Aug 14 '18 at 06:57
  • @Magic_Whizz it's not in the xml.... study this: https://www.101apps.co.za/articles/passing-data-between-activities.html – Angus Aug 14 '18 at 06:59
  • where you have `"dropdown"` is that the variable name of the spinner? and when you say `dropdown_value` what would that be? –  Aug 25 '18 at 06:43
  • 2
    My bad, I mean spinner, just use the onItemSelected of the spinner, and have a variable in that method, once the user select, it will store the selected value to a variable and you can do what I wrote up there – Angus Aug 26 '18 at 03:04
  • Thank you. what are the 'i' for? –  Aug 26 '18 at 03:24
  • 2
    you can learn the basic of android programming which is to start another activity from here: https://developer.android.com/training/basics/firstapp/starting-activity – Angus Aug 26 '18 at 03:35
  • thanks for the link. I put `Intent i= new Intent(this, view.class);` but it is underlined red. –  Aug 26 '18 at 03:40
  • 1
    No problem, but it is advisable that you learn the simple basic before go advance, as you might not understand most of the answer here, with better understanding of basic you will be easy to do whatever you want. Mark as answer if i have helped you. happy coding – Angus Aug 26 '18 at 03:42
  • :) how come it does not recognise my `view.class` ? It is like what is in the example link you showed me. –  Aug 26 '18 at 03:44
  • done. error log just said ( was expected...but in the code it says different –  Aug 26 '18 at 03:49
  • 1
    @Magic_Whizz updated here, take note, all notable things are commented in the code – Angus Sep 04 '18 at 08:04
1
buttonGo.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
if(spinner!=null){

Intent i= new Intent(create.this, viewscreen.class);
//Create the bundle
Bundle bundle = new Bundle();

//Add your data to bundle
bundle.putString("dropdown", dropdown_value);

//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
             }
         });
Angus
  • 3,680
  • 1
  • 12
  • 27
  • Ok. I think I have stuffed up the brackets somewhere because the code is in the onCreate, but the spinner is still not recogniseable? –  Aug 26 '18 at 05:34
  • that's why u check the spinner is null or not, if not it wont go to other activity – Angus Aug 26 '18 at 05:34
  • oh ya, define your spinner like how you define your button – Angus Aug 26 '18 at 05:37
  • I added `SearchableSpinner spinner = new SearchableSpinner(this);` in the buttonGo code. (i got this code which I have in the makeSpinner method) but **this** is underliend red** –  Aug 26 '18 at 05:42
  • .... speechless.... just remove final Spinner from final Spinner spinner under your onClick, and declare the variable global – Angus Aug 26 '18 at 05:45
1
public class create extends AppCompatActivity {

private LinearLayout mLinearLayout;
private ArrayList<SearchableSpinner> mSpinners;
//TODO add the below list of buttons and checkboxes
// private List<AppCompatButton> mButtons = new ArrayList<>();
private List<CheckBox> mCheckboxes = new ArrayList<>();
private List<View> mViews = new ArrayList<>();
Button buttonGo;
Spinner spinner;
......
floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();

            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            // Handle the click.


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

            spinner = makeSpinner();
}
Angus
  • 3,680
  • 1
  • 12
  • 27
  • I got an error from logcat. Updated it in the post –  Aug 26 '18 at 05:57
  • did u update all your code? So I can know which line could possibly happen – Angus Aug 26 '18 at 05:59
  • 1
    updated code now. it happens on the line where I declare buttonGo onclicklistener –  Aug 26 '18 at 06:01
  • 2
    I guess you forgot to do assignment: (Button) findViewById(R.id.buttongo); something like this – Angus Aug 26 '18 at 06:02
  • ok. but I think there is a problem. because when I add some spinners by clicking the FAB and then click the button to go to the viewscreen, none of the spinners are there –  Aug 26 '18 at 06:09
  • you have to reassign the value u get from the previous activity and set it in the new activity... lmao – Angus Aug 26 '18 at 06:11
  • how do I go about doing that ? isn't that what we put in the viewscreen java code? –  Aug 26 '18 at 06:12
  • yes! did you declare the spinner like in create in viewscreen? did u set the value in viewscreen? from what we talk about before, you just passing value, you need to get the value and assign to the spinner............... I thought you should know all this, new activity of course is empty in there – Angus Aug 26 '18 at 06:18
  • ok..will do. but does it matter that these spinners are being programatically added? like when I press the FAB , the spinners are added. Does this matter or will it still work. Are the spinners themselves being copied over too right? –  Aug 26 '18 at 06:35
  • they are not copied... you are just passing values to it, the behaviour of the spinner is not defined... – Angus Aug 26 '18 at 06:38
  • no but like, when you press the button in the bottom right, a spinner appears and you can add as many spinners as you want (on the create screen) then when you click that other button I just made to go to the view screen, will all those spinner appear there? even though they were programatically duplicated if you get what I mean –  Aug 26 '18 at 06:55
  • then what's the point you go to another activity? mind as well you do everything in 1 – Angus Aug 26 '18 at 07:21
  • hi again Angus, I think I will be using your solution. i'll try put it in my code again,. are you able to put all your posts into one post so it is easier to see? –  Sep 04 '18 at 07:20
1

I don't know why you are stuck in this problem still. When you know to pass values in Activities. If I think about your problem, I get various solutions in my mind.

Solution 1: Use @Angus solution, I checked your code when you followed his answer.

Basically you have to pass an value to next activity, like position/ spinner selected value.

bundle.putString("selectedPos", spinner.getSelectedItemPosition());

or

bundle.putString("selectedItem", ((String) spinner.getSelectedItem()));

Solution 2: You have SharedPreference to store these values in first activity, then get saved values in second activity.

Solution 3: I don't suggest to use Application class to store variables, but yes!, that's a solution. Like this answer. I don't use Application class to store values, because we need to clear the fields after use manually, to recover RAM uses.

Solution 4: As you said both of your Activities are almost same, then why don't you just use one Activity and manage Views accordingly.

Edit

If I am getting right, then you can pass the generated Spinners items list and selected items to next Activity. You can pass Parcelable List for ease.

First Activity passes the Spinner model list.

ArrayList<ModelSpinner> list = new ArrayList<>();
list.add(new ModelSpinner(itemsList, (String) spinner.getSelectedItem()));
startActivity(new Intent(this, MainActivity.class).putParcelableArrayListExtra("key", list));

Second activity gets the list and make according views

ArrayList<ModelSpinner> list = getIntent().getParcelableArrayListExtra("key");
for (ModelSpinner spinner : list) {
//            render spinners
    Spinner spinner = makeSpinner(spinner.getItems(),spinner.getSelectedValue());
    // todo create method makeSpinner(List<String> list, String selectedItem), add this spinner to your activity.
}

ModelSpinner.class

public class ModelSpinner implements Parcelable {
    private ArrayList<String> items;
    private String selectedValue;

    // getter setter

    public ModelSpinner(ArrayList<String> items, String selectedValue){
       this.items = items;
       this.selectedValue = selectedValue;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringList(this.items);
        dest.writeString(this.selectedValue);
    }

    public ModelSpinner() {
    }

    protected ModelSpinner(Parcel in) {
        this.items = in.createStringArrayList();
        this.selectedValue = in.readString();
    }

    public static final Parcelable.Creator<ModelSpinner> CREATOR = new Parcelable.Creator<ModelSpinner>() {
        @Override
        public ModelSpinner createFromParcel(Parcel source) {
            return new ModelSpinner(source);
        }

        @Override
        public ModelSpinner[] newArray(int size) {
            return new ModelSpinner[size];
        }
    };
}
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • I get how to get the selected item values from the spinner, but what about the actual spinner itself? because these spinners are being programatically added when you press a button –  Aug 28 '18 at 06:16
  • also, I want two separate activites so the user can easily differentiate between the two i.e one is where you create your shopping list and the other is where you view it, and there will be other functionalities in the view activity too. –  Aug 28 '18 at 06:25
  • As you want to send complete view to another activity. It is not possible, but you can send the related data to next activity, Like you sent spinner list, selected item. and rendered a spinner on next activity by the received fields. – Khemraj Sharma Aug 28 '18 at 06:43
  • what do you mean by `and rendered a spinner on next activity by the received fields` ? Do you mean that, say create 5 spinners in create screen and select values from them, then to put those on the view screen I'd make my program make the amount of spinners equal to the number of values stored? Then it puts those values in the spinners? –  Aug 28 '18 at 06:46
  • Hey see my answer please for an example. – Khemraj Sharma Aug 28 '18 at 06:59
  • thanks for that. could you add some comments/TODOs in the code though, it would help –  Aug 28 '18 at 07:21
  • 1
    You already know how to add Spinner to view, you just need to iterate the received list, and create spinners programmatically. I am adding some Todo as well. – Khemraj Sharma Aug 28 '18 at 07:24
  • i'm just confused how to add those values to the spinners? –  Aug 31 '18 at 04:54
  • hello? so If I am correct about your code you posted here.: you are getting the values from the multiple spinners then you are putting them into an array list. then on the second activity are you getting the number of values you have saved in your list then creating that number of spinners, then you are putting those saved values in those spinners? am I right here? –  Sep 03 '18 at 06:39
  • don't know if this tags you –  Sep 03 '18 at 06:42
  • 1
    Yes, you can say that!, Actually I showed you way to pass all the values you need to next activity, because you can not just pass all view objects, so you need to pass the related values, and then on next activity just get those values (selected items/ all items) and re-create view. – Khemraj Sharma Sep 03 '18 at 07:07
  • thanks :D so in the code you have posted, where does it have about the spinners and creating the number of spinners the same as the number of values? or is that not in there. How would I go about doing that? –  Sep 03 '18 at 07:08
  • Your purpose is to show all first activity's spinners to next activity, with same selected values. Right?, So you are already creating spinners, so now in next activity, first create spinner with received values and then call `spinner.setSelection(selectedPosition)` . – Khemraj Sharma Sep 03 '18 at 07:13
  • yes correct. but yes, I know how to create spinners like how i am but how do I create the number of spinners i Need to fit the number of values i have? like say I added 3 spinners in the create screen and added values to them. then i go to view screen. how do I know to programatically create 3 spinners? –  Sep 03 '18 at 07:15
  • 1
    You are getting `ArrayList` in next activity, so just loop on this List and create spinners – Khemraj Sharma Sep 03 '18 at 07:16
  • can I use a `for` loop for that or something? sorry I've never really used loops in Android before –  Sep 03 '18 at 07:52
  • also this line ` list.add(new ModelSpinner(itemList, (String) spinner.getSelectedItem()));` gives be an error 'cannot resolve constructor ModelSpinner' –  Sep 03 '18 at 07:59
  • I thought you will understand this, I edited my answer, see constructor in ModelSpinner. Also the answer is just an way to solve, please edit as your requirement. Also create getter setter inside ModelSpinner. – Khemraj Sharma Sep 03 '18 at 10:06
  • What do I put for getter setter? –  Sep 03 '18 at 10:30
  • You seem very new to Android/ Java, Please check https://stackoverflow.com/q/23897215/6891563 – Khemraj Sharma Sep 03 '18 at 10:38
  • sorry. what does it mean when it says 'modelspinner cannot be applied to (java.util.list) ? –  Sep 03 '18 at 19:10
  • I have edited the variables to my requirement thanks –  Sep 03 '18 at 19:11
1

The best solution for this scenario will be using ViewModel and LiveData from architectural components library which will simply provide you consistency in data in both the Activities. A single ViewModel for both Activities and shared LiveDatas for both Activities which will be helpful when you update any LiveData from any Activity it will get reflected in all the Activities which is observing the defined LiveData in the ViewModel.

1

You are calling the context as "This" but is calling it from within a method that overwrites a method in the interface, but the method is not in this class and therefore does not know what "This" is, to solve it do this, in you Create Class:

public class Create extends AppCompatActivity {
  private Context context;
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        context = this;
        buttonGo.setOnClickListener(new View.OnClickListener() {
                                        public void onClick(View v) {

                                            if(spinner!=null){

                                                Intent i= new Intent(context, View.class);
                                                startActivity(i);
                                            }
                                        };
  }
}

You can pass data with the intent,or can pass data using a static variable in the Create class.

Create Class:

    public class Create extends AppCompatActivity {
        public static String optionSelected;
//other code....
            spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                          Create.optionSelected = parent.getItemAtPosition(position).toString();  
                        }
                    });
//other code....

            }

In your View Class to call optionSelected:

public class View extends AppCompatActivity {

 String dropdown_value= Create.optionSelected;

  // rest of code
}

If you want to use a Category Adapter Class:

public class CategoryAdapter extends FragmentPagerAdapter {

    public CategoryAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new CreateFragment();
            case 1:
                return new ViewFragment();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 2;
    }
}
  • I have kind of gone back to my previous code; i,e I don't really want it so there's `buttonGo` which takes you from create > view.I just want it like Main > create, main > view. is it still possible to do this way –  Aug 31 '18 at 06:32
  • like I mean, without using startActivity –  Sep 03 '18 at 06:36
  • Hello @Magic_Whizz I need to see your create_layout.xml and how do you want it to look? – Santiago Celada Gonzalez Sep 03 '18 at 08:35
  • I think you should use fragment and a Category Adapter class, please show me your layout xml, I explain to you how it is done. Please see the my edit answer, to see a Category Adapter class. – Santiago Celada Gonzalez Sep 03 '18 at 08:42
  • i have added my layout xml, but it doesn't say much because i am programatically adding spinners when the user presses the FAB. thanks, I'll have a look at your code :) –  Sep 03 '18 at 08:50
0

I think what you want to do is pass the user selected items from the create screen to the view screen.

You can use a global class to store the values of the selected items. And use it like a normal java class.

public class GlobalClass extends Application {
    ArrayList<String> items = new ArrayList<>();

    public ArrayList<String> getItems() {
        return items;
    }

    public void setItems(ArrayList<String> items) {
        this.items = items;
    }
}

Define this in the application tag of the manifest file

<application
    android:name=".GlobalClass"

and use it like this in the onCreate function of both activities

globalClass = (GlobalClass) this.getApplicationContext();

then you can use getters and setters to access your selected item list. in create activity,

ArrayList<String> items = new ArrayList<>();
items.add(item); // add you selected item
globalClass.setItems(items);

in view activity,

ArrayList<String> items = globalClass.getItems();
NirmalCode
  • 2,140
  • 1
  • 14
  • 19
  • Where abouts in the manifest file do I define android:name=".GlobalClass"? –  Aug 14 '18 at 07:04
  • 1
    in the application tag ` – NirmalCode Aug 14 '18 at 07:14
  • I don't have `item` –  Aug 14 '18 at 07:22
  • 1
    item = object or the string value of your selected item or items from the dropdowns as you mentioned – NirmalCode Aug 14 '18 at 07:24
  • thanks. When I usethat code, then run my app I go into create activity and add select item from a dropdown, then I go to the view screen, but the dropdown isn't there? –  Aug 14 '18 at 07:48
  • 1
    Sorry, I didn't understand what you are asking. – NirmalCode Aug 14 '18 at 07:59
  • 1
    But if you are asking about the dropdowns you selected from the create view, You have to create them using the data that is passed using this global class. And btw, you can store the data for dropdowns in the global class and access them from both views. – NirmalCode Aug 14 '18 at 08:07
  • how do I go about doing that –  Aug 23 '18 at 05:59
  • hi? it would be great if I could have your help , thank you! –  Aug 26 '18 at 04:35
  • No, don't do this. This is an shockingly bad solution that should not be spread. Android provides basic ways to do accomplish what OP needs without the need to bloat the application class, break encapsulation and resist learning – Nick Cardoso Aug 30 '18 at 12:03
0

I had a similar requirement. I solved it with a different logic.

  1. Create a class for reference.
  2. Store data in this class, then stringify using Gson and pass it to second activity.
  3. Get back from stringified json to class object using Gson.
  4. OnCreate, update the UI according to the object content u received in Step 3.

This will make the flow in control and development friendly. Hope this serves your requirement well.

Storing the view and transferring is not a better idea since this can lead to development complexity later.

Incase of multiple data for n number of spinners, you can use ArrayList of product objects and create spinner view dynamically.

Shibu Murugan
  • 31
  • 1
  • 8
-1

Alright so what I suggest doing is create an ArrayList of Integer to keep track of both the number of Spinners you created in the first Activity through ArrayList.size() and the position of each spinner which would be the value in the ArrayList.

So first when a button is clicked in the first Activity put this code in the onClick method:

ArrayList<Integer> spinnerList = new ArrayList<>(); 
for(int i = 0; i < mSpinners.size(); i++) { 
    spinnerList.add(mSpinners.get(i).getSelectedItemPosition()); 

} 
Bundle newBundle = new Bundle(); 
newBundle.putIntegerArrayList("arraylist", spinnerList); 
Intent newIntent = new Intent(create.this, view.class); 
newIntent.putExtra("extraBundle", newBundle);
startActivity(newIntent);

And then in the second Activity (view Activity) get the ArrayList like this:

Intent gotIntent = getIntent();
Bundle bundle = getIntent().getBundleExtra("extraBundle");
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");

After getting the ArrayList create a For loop same number of times as the size of the ArrayList which is the number of spinners you had and add the code for adding the spinner and other views:

for(int i = 0; i < spinnerArrayList.size(); i++ { 
    //code for adding all views 

    //at the end of the loop 
    int positionOfSpinner = spinnerArrayList.get(i); 
    spinner.setSelection(positionOfSpinner);

}
Mr.O
  • 813
  • 7
  • 14