0

My question is i have a list of food item. when user press add button to add the dish i am saving this dish name in shared preference. but when i press the same dish twice in shared preference should show 2 dishes with the same name. but each time i press same dish its showing me only one dish. this is my code below.

public class Cafetaria extends AppCompatActivity {


    String title;
    ListView listView;
    View customNav;
    public String value,secdish,thrDish,frthDish;
    public String Drink,Drink2,Drink3,Drink4;
    String selectedDrink;
    Dialog ViewDialog;
    TextView tv_foodtype,tv_drink;
    private Button button;

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

        title = getIntent().getStringExtra("option");
        getSupportActionBar().setTitle(title);

        ActionBar actionBar = getSupportActionBar();
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        customNav = LayoutInflater.from(this).inflate(R.layout.food_actionbar_layout, null); // layout which contains your button.

        actionBar.setCustomView(customNav, lp);
        actionBar.setDisplayShowCustomEnabled(true);

        customNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ViewDialog = new Dialog(Cafetaria.this);
                ViewDialog.setContentView(R.layout.activity_order_detail);
                ViewDialog.setTitle("Your Order Details");


                tv_foodtype = (TextView)ViewDialog.findViewById(R.id.nameuser);
                tv_drink = (TextView)ViewDialog.findViewById(R.id.passnum);
                button = (Button)ViewDialog.findViewById(R.id.okBtn);
                ViewDialog.show();

                final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                value=(mSharedPreference.getString("firstDish", ""));

                Drink=(mSharedPreference.getString("selectedDrinks", ""));
                Drink2=(mSharedPreference.getString("selectedDrinks1", ""));
                Drink3=(mSharedPreference.getString("selectedDrinks2", ""));
                Drink4=(mSharedPreference.getString("selectedDrinks3", ""));

                secdish=(mSharedPreference.getString("secdish", ""));
                thrDish=(mSharedPreference.getString("thirdDish", ""));
                frthDish=(mSharedPreference.getString("fourtDish", ""));


                tv_foodtype.setText("Main Dishes"+ " \n"+value + " \n" + secdish +"\n"+thrDish+"\n"+frthDish);
                tv_drink.setText("Drink"+" \n"+Drink + " \n" + Drink2 +"\n"+Drink3+"\n"+Drink4);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        ViewDialog.dismiss();


                    }
                });


            }
        });



        listView =(ListView)findViewById(R.id.listView);

        Drawable chic = this.getResources().getDrawable(R.drawable.chicktikka);
        final Drawable plus = this.getResources().getDrawable(R.drawable.plus);
        Drawable minus = this.getResources().getDrawable(R.drawable.minus);

        ArrayList<FoodItemData> listofItem = new ArrayList<>();
        FoodListViewAdapter listViewAdapter= new FoodListViewAdapter(this,R.layout.item_layout,listofItem);
        listView.setAdapter(listViewAdapter);

        listofItem.add(new FoodItemData("Chicken Tikka","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
        listofItem.add(new FoodItemData("Onion Bhaji","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
        listofItem.add(new FoodItemData("Chicken Pizza","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
        listofItem.add(new FoodItemData("Chicken Masala","spicey chicken tikka with mixures of indian spices",chic,plus,minus));

    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR1)
    public void plusClick(View v)
    {
        if (listView.getPositionForView(v)==0) {


            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
            final SharedPreferences.Editor editor = prefs.edit();


            editor.putString("firstDish","Chicken Tikka");
            AlertDialog.Builder adb = new AlertDialog.Builder(this);
            adb.setTitle("Please Choose your drink");
            final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};

            final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
            final boolean[] preCheckedItems = new boolean[]{false, false, false};

            adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if (isChecked) {
                        selectedItems.add(which);
                    } else if (selectedItems.contains(which)) {
                        selectedItems.remove(which);
                    }
                }
            });

            //Define the AlertDialog positive/ok/yes button
            adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    for (int i = 0; i < selectedItems.size(); i++) {
                        int IndexOfColorsArray = selectedItems.get(i);
                        selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);

                        editor.putString("selectedDrinks",selectedDrink);
                        editor.commit();

                    }

                    Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();

                }
            });

            //Define the Neutral/Cancel button in AlertDialog
            adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            adb.show();
        }

     else if (listView.getPositionForView(v) == 1) {

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
            final SharedPreferences.Editor editor = prefs.edit();
            editor.putString("secdish","Onion Bhaji");

            AlertDialog.Builder adb = new AlertDialog.Builder(this);
            adb.setTitle("Choose your Drink");
            final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
            final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
            final boolean[] preCheckedItems = new boolean[]{false, false, false};

            adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                    if (isChecked) {
                        selectedItems.add(which);
                    } else if (selectedItems.contains(which)) {
                        selectedItems.remove(which);
                    }
                }
            });

            //Define the AlertDialog positive/ok/yes button
            adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    for (int i = 0; i < selectedItems.size(); i++) {
                        int IndexOfColorsArray = selectedItems.get(i);
                        selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
                        editor.putString("selectedDrinks1",selectedDrink);
                        editor.commit();

                    }

                    Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();

                }
            });
            adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //When user click the neutral/cancel button from alert dialog
                }
            });
            adb.show();
     }


        else if (listView.getPositionForView(v) == 2) {

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
            final SharedPreferences.Editor editor = prefs.edit();
            editor.putString("thirdDish","Chicken Pizza");

            AlertDialog.Builder adb = new AlertDialog.Builder(this);
            adb.setTitle("Choose your Drink");
            final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
            final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
            final boolean[] preCheckedItems = new boolean[]{false, false, false};

            adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                    if (isChecked) {
                        selectedItems.add(which);
                    } else if (selectedItems.contains(which)) {
                        selectedItems.remove(which);
                    }
                }
            });

            adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    for (int i = 0; i < selectedItems.size(); i++) {
                        int IndexOfColorsArray = selectedItems.get(i);
                        selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
                        editor.putString("selectedDrinks2",selectedDrink);
                        editor.commit();

                    }

                    Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
                }
            });
            adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //When user click the neutral/cancel button from alert dialog
                }
            });
            adb.show();
        }

        else if (listView.getPositionForView(v) == 3) {

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
            final SharedPreferences.Editor editor = prefs.edit();
            editor.putString("fourtDish","Chicken Masala");

            AlertDialog.Builder adb = new AlertDialog.Builder(this);
            adb.setTitle("Choose your Drink");
            final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
            final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
            final boolean[] preCheckedItems = new boolean[]{false, false, false};

            adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                    if (isChecked) {
                        selectedItems.add(which);
                    } else if (selectedItems.contains(which)) {
                        //selectedItems.remove(which);
                        selectedItems.add(which);
                    }
                }
            });

            adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    for (int i = 0; i < selectedItems.size(); i++) {
                        int IndexOfColorsArray = selectedItems.get(i);
                        selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
                        editor.putString("selectedDrinks3",selectedDrink);
                        editor.commit();

                    }

                    Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
                }
            });
            adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //When user click the neutral/cancel button from alert dialog
                }
            });
            adb.show();
        }

 }

    public void minusClick(View v)
    {
        if (listView.getPositionForView(v)==0) {

            final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            mSharedPreference.edit().remove("firstDish").commit();
            mSharedPreference.edit().remove("selectedDrinks").commit();
            Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
        }

        else if (listView.getPositionForView(v)==1)
        {
            final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            mSharedPreference.edit().remove("secDish").commit();
            mSharedPreference.edit().remove("selectedDrinks1").commit();
            Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
        }
        else if (listView.getPositionForView(v)==2)
        {
            final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            mSharedPreference.edit().remove("thirdDish").commit();
            mSharedPreference.edit().remove("selectedDrinks2").commit();
            Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
        }
        else if (listView.getPositionForView(v)==3)
        {
            final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            mSharedPreference.edit().remove("fourtDish").commit();
            mSharedPreference.edit().remove("selectedDrinks3").commit();
            Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getSupportActionBar() != null){
            getSupportActionBar().setTitle(title);
        }



    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case android.R.id.home:
                this.finish();
                return true;

        }


        return false;

    }

    @Override
    protected void onRestart() {
        super.onRestart();

        final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        mSharedPreference.edit().remove("firstDish").commit();
        mSharedPreference.edit().remove("selectedDrinks").commit();
        mSharedPreference.edit().remove("selectedDrinks1").commit();
        mSharedPreference.edit().remove("selectedDrinks2").commit();
        mSharedPreference.edit().remove("selectedDrinks3").commit();
        mSharedPreference.edit().remove("secdish").commit();
        mSharedPreference.edit().remove("thirdDish").commit();
        mSharedPreference.edit().remove("fourtDish").commit();


    }


}`

This is the result I am getting. I press this dish twice and its shown only once. It should be shown twice the same dish name. Please Guide.

enter image description here

Surya Prakash Kushawah
  • 3,185
  • 1
  • 22
  • 42

1 Answers1

0

The code is really long to follow on here. But speaking generally, do you save each dish with different key-value pair? Maybe think about such solution. OR you could store the dishes in an array, which can be stored in Shared prefs, and once you want to see your dishes, just read out the Array List and display the items inside it.

You store the String into an Array, whenever you want to do it in your code. It's just like mArrayList.add("String"); and then you can update yuor SharedPrefs the same you already do, just check the URL on how to store ArrayList to SharedPrefs. Would be a cleaner solution in my view.

Here you can see how to store ArrayList in SharedPreferences: Save ArrayList to SharedPreferences

And the once you want to display the items from ArrayList, you pull ArrayList from SharedPrefs and display them in AlertDialog ListView.

And here it is explained how to display Array Items in AlertDialog: How can I display a list view in an Android Alert Dialog?

Community
  • 1
  • 1
David Kasabji
  • 1,049
  • 3
  • 15
  • 32
  • i tried this way a lot but still is showing only on item. is there any other way you can explain through code will be a huge help thanks. – Barry O'Reilly Dec 15 '16 at 11:41
  • I would create an ArrayList of String. When user selects a Dish I would extract the ID of it and Store the String name of the dish in ArrayList. I wuold update shared prefference after each such occurence with the updated ArrayList. And whenever user wants to pull the info from SharedPrefs, I would pull out my ArrayList of it. Get the Lenght of it and iterate over each item within it and display each string in list. – David Kasabji Dec 15 '16 at 11:48
  • can u explain in code please will be a huge support. many thanks – Barry O'Reilly Dec 15 '16 at 11:49
  • I dont have time now to check the codes, but I gave you some URLs which might help you with code examples on how to display it better in your case. – David Kasabji Dec 15 '16 at 12:02