Saturday, 8 September 2018

Using the number values in 'TextViews' to order them in number order

BACKGROUND

So I have a create and view screen. On the create screen, the user presses the FAB, then a spinner, textview, edittext and checkbox appear. when the user presses the fab again, these set of elements appear again. you can add as many set of elements as you want.

Then when you click to overflow menu and click one of the items in it, it takes you to the 'view' screen, in which all the values and spinners and elements you selected from the create screen, are shown on this view screen.

Additionally, when the user selects values from each spinner, the textview displays a number which is related to that item. Say you pick 'bread' in the spinner, then in the textview it shows '4'. (These are just aisle numbers for shop items btw)

PROBLEM

On the view screen, I am trying to make it so when the user goes on to the view screen, each 'set of elements' are ordered in number order of the textview

So example on the create screen this is what it looks like (number is the viewtext, item is the spinner)

Toast 8 EditText Checkbox

Spread 2 EditText Checkbox

Chocolate 5 EditText Checkbox

Then when the user goes onto the view screen I want it so it's like:

Spread 2 EditText Checkbox

Chocolate 5 EditText Checkbox

Toast 8 EditText Checkbox

If you get what I mean. if further clarification is needed let me know.

view.java code

public class view 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<>();
    private Spinner spinner;
    private TextView textview;
    private CheckBox checkbox;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        GlobalClass globalClass = (GlobalClass) this.getApplicationContext();
        textview = findViewById(R.id.textview);
        checkbox = findViewById(R.id.checkbox);
        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);





        Intent gotIntent = getIntent();
        Bundle bundle = getIntent().getBundleExtra("extraBundle");

        ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");


        //creating a for loop, to create the number of spinners in the spinnerarray list size
        for(int i = 0; i < spinnerArrayList.size(); i++) {
            final Spinner spinner = makeSpinner();
            mLinearLayout.addView(spinner);

            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 CheckBox newCheckbox = makeCheckbox();
            mLinearLayout.addView(newCheckbox);

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

            //setting spinner selection values
            int positionOfSpinner = spinnerArrayList.get(i);
            spinner.setSelection(positionOfSpinner);




        }









            //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();
                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(view.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);



                newCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // makes the set disappear when checkbox is ticked.

                        newCheckbox.setVisibility(View.VISIBLE);
                        spinner.setVisibility(View.VISIBLE);
                        newView.setVisibility(View.VISIBLE);

                        newCheckbox.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                newCheckbox.setVisibility(View.GONE);
                            }
                        });



                        spinner.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                spinner.setVisibility(View.GONE);
                            }
                        });

                        newView.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                newView.setVisibility(View.GONE);
                            }
                        });



                    }
                });






                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
                    }

                });


            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.create_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Intent startSettingsActivity = new Intent(this, AppCompatPreferenceActivity.class);
            startActivity(startSettingsActivity);
            //start the settings activity here.
            return true;
        }


        else if (id == R.id.action_delete) {
            //code to delete list here.
            return true;

        }



        return super.onOptionsItemSelected(item);
    }





    //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
        Resources resources = getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams((int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)), (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)));
        relativeParams.addRule(RelativeLayout.RIGHT_OF, R.id.textview);


        checkbox.setLayoutParams(relativeParams);

        // RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(relativeParams.addRule(RelativeLayout.RIGHT_OF, R.id.textview));

        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.setTextSize(30);



        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);
        edittext.setHint("qty");

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



from Using the number values in 'TextViews' to order them in number order

No comments:

Post a Comment