R
R
Redry2019-05-16 23:20:31
Java
Redry, 2019-05-16 23:20:31

How to add data to different SQLite tables?

I'm trying to create a small application to track the number of working hours per month. A separate table with data is created for each month. Table names - the month-year for which this table is responsible. A table with two columns: ID - the day of the month, and time - the hour.
The top button calls the date picker method. The selected date is indicated as text on the button itself, the value is also taken from the table and displayed as text on the second button.
The bottom button calls up a window for entering the number of hours, after entering this value is entered into the table and put as text on the button itself.

spoiler
5cddc4f1f0393129959774.jpeg5cddc502c6736041430245.jpeg5cddc50ee0daa277873533.jpeg

If the current month is selected, then everything works fine, but if I select any day of another month, then I cannot put the value into another table created for another month. I can't understand the reason at all. MainActivity Method
spoiler
public class MainActivity extends AppCompatActivity implements callDialogListener{

    final Context context = this;
    private TextView sumMonth;
    private Button btnDate;
    private Button btnHour;

    Calendar cal = Calendar.getInstance();
    private int mYear= cal.get(Calendar.YEAR);
    private int mMonth = cal.get(Calendar.MONTH) + 1;
    private int mDay = cal.get(Calendar.DAY_OF_MONTH);
    //Строка для именования таблиц " месяц.год"
    private String[] whereArgs = {getDateName(mMonth, mYear)};

    private WorkTimeDbHelper timeHelper = new WorkTimeDbHelper(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnDate = (Button)findViewById(R.id.btnDate);//Кнопка выбора даты
        btnHour = (Button)findViewById(R.id.btnHour);//Кнопка ввода часов
        sumMonth = (TextView)findViewById(R.id.hourSum);
        btnHour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callDialog();
            }
        });
        btnDate.setText("" + mDay + "." + mMonth + "." + mYear);
        btnDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePick();
            }
        });

        chekTable();
        btnHour.setText(Integer.toString(getTableValues(mDay,mMonth, mYear)));
    }
    //Метод для ввода количества часов
    @Override
    public void callDialog() {
        LayoutInflater inflater = LayoutInflater.from(context);
        View lay = inflater.inflate(R.layout.num_dialog, null);
        final AlertDialog.Builder numDialog = new AlertDialog.Builder(context);
        numDialog.setView(lay);
        final TextView numText = (TextView)lay.findViewById(R.id.numText);
        numDialog.setTitle("Ведите количество часов");
        numDialog.setCancelable(false);
        numDialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int id){
                String textNum = numText.getText().toString();
                if(textNum.equals(""))textNum = "0";
                insertValue(textNum, mDay, mMonth, mYear);
                btnHour.setText("" + getTableValues(mDay,mMonth, mYear));
            }
        });
        numDialog.setNeutralButton("отмена", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        numDialog.create();
        numDialog.show();
    }

    //Метод для выбора даты
    @Override
    public void datePick(){

        LayoutInflater inflater = LayoutInflater.from(context);
        View lay = inflater.inflate(R.layout.date_pick, null);
        final AlertDialog.Builder dateDialog = new AlertDialog.Builder(context);
        final CalendarView calendar = (CalendarView)lay.findViewById(R.id.calendar);
        dateDialog.setView(lay);
        calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                mYear = year;
                mMonth = month + 1;
                mDay = dayOfMonth;
                chekTable();
                btnHour.setText("" + getTableValues(mDay,mMonth, mYear));
            }
        });
        dateDialog.setCancelable(false);
        dateDialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int id){
                btnDate.setText("" + mDay + "." + mMonth + "." + mYear);
            }
        });
        dateDialog.create();
        dateDialog.show();
    }
    public int getmYear(){
        return mYear;
    }
    public int getmMonth(){
        return mMonth;
    }
    public int getmDay(){
        return mDay;
    }

    //Проверить, есть ли таблица для хранения данных выбранного месяца, если таблицы нет, то создать ее
    public void chekTable(){

        SQLiteDatabase db = timeHelper.getReadableDatabase();
        String[] columns = {timeHelper.MONTH};
        String WHERE = WorkTimeDbHelper.MONTH + "=?";
        String[] Args = {getDateName(mMonth, mYear)};
        //Проверка есть ли в главной таблице запись с названием таблицы месяца
        Cursor cursor = db.query(
                WorkTimeDbHelper.MAIN_TABLE,
                columns,
                WHERE,
                Args,
                null,
                null,
                null);
        //Если запись есть, то i = 1
        int i = cursor.getCount();
        cursor.close();

        if(i == 0){
            String CREATE_TABLE = "CREATE TABLE " + Args[0] + " ("
                    +WorkTimeDbHelper._ID + " INTEGER, "
                    +WorkTimeDbHelper.TIME + " INTEGER NOT NULL DEFAULT 0 );";
            db.execSQL(CREATE_TABLE);
            int hours = 0;

            db = timeHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            for(int x = 0; x < 32; x++) {
                values.put(WorkTimeDbHelper._ID, x+1);
                values.put(WorkTimeDbHelper.TIME, hours);
                db.insert(whereArgs[0], null, values);
            }
            //Добавляет в главную таблицу название новой таблицы месяца
            ContentValues values2 = new ContentValues();
            values2.put(WorkTimeDbHelper.MONTH, Args[0]);
            db.insert(WorkTimeDbHelper.MAIN_TABLE, null, values2);
        }
    }
    //Метод создающий строку для именования таблиц "месяц.год"
    public String getDateName(int mMonth, int mYear){
        String s = "A" + Integer.toString(mMonth) + "x" + Integer.toString(mYear);
        return s;
    }
    //Метод для получения значения из нужной ячейки нужной таблицы
    //В качестве параметра принимает дату, чтобы по ней найти нужную таблицу и строку в таблице
    public int getTableValues(int day, int month, int year){
        SQLiteDatabase db = timeHelper.getReadableDatabase();
        String NAME_TABLE = getDateName(month, year);
        String colomns[] ={WorkTimeDbHelper.TIME};
        String WHERE = WorkTimeDbHelper._ID + "=?";
        String idValue[] = {Integer.toString(day)};
        Cursor cursor = db.query(
                NAME_TABLE,
                colomns,
                WHERE,
                idValue,
                null,
                null,
                null);
        int currentID = 0;
        int indexID = cursor.getColumnIndex(WorkTimeDbHelper._ID) + 1;
        if (cursor.moveToFirst()){
            do{
                currentID = cursor.getInt(indexID);
                cursor.close();
            }while (false);
        }
        return currentID;
    }
    //Метод для добавления данных в таблицу
    public void insertValue(String text, int day, int month, int year){
        int value = Integer.parseInt(text);
        SQLiteDatabase db = timeHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        String TABLE_NAME = getDateName(month, year);
        String idValue[] = {Integer.toString(day)};
        values.put(WorkTimeDbHelper.TIME, value);
        db.update(TABLE_NAME, values,
                WorkTimeDbHelper._ID + "=?", idValue);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2019-05-16
@longclaps

A separate table with data is created for each month.

Marasmus.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question