Search code examples
androidsqldatabasesqlitesqliteopenhelper

How to save data in a few places


how can I put data from my database in several places to save different data. I do not know if this is a completely understandable question, which is why I will try to bring them a bit closer.

I would like to save the names of dishes for each day of the week:

i.e. i have a list with the names of the days of the week: - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, - Sunday

and now I would like to save various dishes there when choosing a particular day. Eg on Monday, chop + potatoes, Tuesday - spaghetti etc. I know that I will have to use different tables to put information there, but I do not know how to do it if I want to write something else each day. Do I have to create a separate Activity for each day of the week and create separate tables for a specific day there?

I did not put in any code, I do not have a problem with it, just the problem I can not get to know.


Solution

  • I know that I will have to use different tables to put information there

    Not necessarily:-

    • You could have a column in the dishes table for each day of the week.

    • You could have a single column that could be used for all days of the week.

      • e.g. if Monday were assigned the value 1, Tuesday 2, Wednesday 4, Thursday 8, 16, 32, 64. (i.e 2 to the power of the day of the week (1-7)).

      • Then if the dish were to be for Monday and Thursday then you could store a single value comprised of logically OR'ing the respective days 1 (Monday) logically OR'd with 8(Thursday) would be 9; adding Friday(16) the stored value would then be 25.

    Assuming the latter, you could then extract (where daysused is the column that indicates the day(s) the dish should appear on the menu):-

    Mondays menu using :-

    SELECT * from dishes WHERE (daysused & 1) > 0
    

    Fridays menu using :-

    SELECT * from dishes WHERE (daysused & 16) > 0
    

    Weekends menu using :-

     SELECT * from dishes WHERE (daysused & (32 | 64)) > 0
    

    Do I have to create a separate Activity for each day of the week and create separate tables for a specific day there?

    No. You could have a general activity, perhaps with a button to select the day of the week or a spinner or a Radio group.

    Clicking/selecting would calculate the day or days which is then used to determine the days to be viewed, this value being fed into the selection criteria along the lines of the above. The resultant Cursor could then be used as the source of a ListView to display the menu.

    Example :-

    The Database Helper

    public class MyMenuDBHelper extends SQLiteOpenHelper {
    
        public static final String DBNAME = "mymenu";
        public static final int DBVERSION = 1;
        public static final String DISHES_TABLE = "dishes";
        public static final String DISHES_ID_COL = BaseColumns._ID;
        public static final String DISHES_NAME_COL = "dishes_name";
        public static final String DISHES_DAYSONMENU_COL = "dishes_daysonmenu";
    
        MyMenuDBHelper(Context context) {
            super(context,DBNAME,null,DBVERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            String crtSQL = "CREATE TABLE IF NOT EXISTS " +
                    DISHES_TABLE + "(" +
                    DISHES_ID_COL + " INTEGER PRIMARY KEY, " +
                    DISHES_NAME_COL + " TEXT, " +
                    DISHES_DAYSONMENU_COL + " INTEGER " +
                    ")";
            db.execSQL(crtSQL);
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
    
        public long addDish(String name,
                       boolean usemonday,
                       boolean usetuesday,
                       boolean usewednesday,
                       boolean usethursday,
                       boolean usefriday,boolean usesaturday, boolean usesunday) {
    
            int daysused = MainActivity.NODAYS_FLAG;
            if (usemonday) daysused = daysused | MainActivity.MONDAY_FLAG;
            if (usetuesday) daysused = daysused | MainActivity.TUESDAY_FLAG;
            if (usewednesday) daysused = daysused | MainActivity.WEDNESDAY_FLAG;
            if (usethursday) daysused = daysused | MainActivity.THURSDAY_FLAG;
            if (usefriday) daysused = daysused | MainActivity.FRIDAY_FLAG;
            if (usesaturday) daysused = daysused | MainActivity.SATURDAY_FLAG;
            if (usesunday) daysused = daysused | MainActivity.SUNDAY_FLAG;
    
            ContentValues cv = new ContentValues();
            cv.put(DISHES_NAME_COL,name);
            cv.put(DISHES_DAYSONMENU_COL,daysused);
            return this.getWritableDatabase().insert(DISHES_TABLE,null,cv);
        }
    
        public Cursor getMenu(int daystoinclude) {
            // SQL SELECT * FROM dishes WHERE (dishes_daysonmenu & the_daystoshow_as_passed) > 0
            Cursor csr = this.getWritableDatabase().query(DISHES_TABLE,null,
                    "(" + DISHES_DAYSONMENU_COL + " &  ?) > 0",
                    new String[]{Integer.toString(daystoinclude)},
                    null,null,null
                    );
            int count = csr.getCount(); //<<< Just for debugging breakpoint
            return csr;
        }
    }
    

    The "Single Activity" - MainActivity

    public class MainActivity extends AppCompatActivity {
    
        public static final String TEST = "test";
        public static final int MONDAY_FLAG = 1 << 0;
        public static final int TUESDAY_FLAG = 1 << 1;
        public static final int WEDNESDAY_FLAG = 1 << 2;
        public static final int THURSDAY_FLAG = 1 << 3;
        public static final int FRIDAY_FLAG = 1 << 4;
        public static final int SATURDAY_FLAG = 1 << 5;
        public static final int SUNDAY_FLAG = 1 << 6;
        public static final int NODAYS_FLAG = 0;
    
        Button[] daybuttonids = new Button[7];
        ListView mMenuList;
        MyMenuDBHelper mDBHelper;
        Cursor mCsr;
        SimpleCursorAdapter mSCA;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            daybuttonids[0] = (Button) this.findViewById(R.id.mon);
            daybuttonids[1] = (Button) this.findViewById(R.id.tue);
            daybuttonids[2] = (Button) this.findViewById(R.id.wed);
            daybuttonids[3] = (Button) this.findViewById(R.id.thu);
            daybuttonids[4] = (Button) this.findViewById(R.id.fri);
            daybuttonids[5] = (Button) this.findViewById(R.id.sat);
            daybuttonids[6] = (Button) this.findViewById(R.id.sun);
            mMenuList = this.findViewById(R.id.menulist);
    
            mDBHelper = new MyMenuDBHelper(this);
            addSomeDishes();
    
            mCsr = mDBHelper.getMenu(NODAYS_FLAG);
            mSCA = new SimpleCursorAdapter(
                    this,   // Context
                    android.R.layout.simple_list_item_1, // layout
                    mCsr, // Cursor
                    new String[]{MyMenuDBHelper.DISHES_NAME_COL}, // column(s)
                    new int[]{android.R.id.text1}, // View
                    0   // flags
            );
            mMenuList.setAdapter(mSCA);
            setButtonListeners();
        }
    
        private void setButtonListeners() {
            for (int i=0; i < daybuttonids.length; i++) {
                daybuttonids[i].setTag(new Integer(i));
                daybuttonids[i].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int daytouse = 1 << Integer.valueOf(v.getTag().toString());
                        Log.d("DAYTOUSE","Day to use is " + Integer.toString(daytouse));
                        refreshList(daytouse);
                    }
                });
            }
        }
    
        private void refreshList(int daystoshowinmenu) {
            mCsr = mDBHelper.getMenu(daystoshowinmenu);
            mSCA.swapCursor(mCsr);
        }
    
        private void addSomeDishes() {
            mDBHelper.getWritableDatabase().delete(MyMenuDBHelper.DISHES_TABLE,null,null);
            mDBHelper.addDish("Chip and Fishes",true,false,false,false,true,false,true);
            mDBHelper.addDish("Egg under Toast", false,true, false, false,false,true,true);
            mDBHelper.addDish("Mashed Bangers", true, false,true,false,true,false,true);
        }
    }
    

    What the App looks like :-

    • Initially (nothing as NODAYS was used for the cursor)

    enter image description here

    • Monday button clicked

    enter image description here

    • Tuesday Button clicked :-

    enter image description here

    • .... Sunday Button clicked :-

    enter image description here

    Of course you could have multiple tables,

    Perhaps you'd have one table for the dishes and another table for the daily menus with the latter having an indicator for the day and the dish (i.e, a reference/link/association to the dish). This would be preferable say if you wanted to keep a tally of dishes served per day as then each combination of dish/day could be uniquely identified and a column could be included for the count of uses.