sqlite 如何将日期、时间、颜色和图像保存到SQL数据库中?

ztmd8pv5  于 2023-04-30  发布在  SQLite
关注(0)|答案(1)|浏览(235)

初级android studio用户程序员在这里;我尝试使用各种YouTube教程编写它,例如 Stevdza-San的SQLite + Android -在数据库表中插入数据(图书库应用程序) 视频,(从第1部分到第2部分)
我正在创建一个应用程序,管理用户的时间,日期和时间,作为一个提醒。色彩为审美,图像为议程的图标。
DatabaseHelper类

package com.ablsv.vremia;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;

 class DatabaseHelper extends SQLiteOpenHelper {

    private final Context context;
     private static final String DATABASE_NAME = "Schedules.db";
     private static final int DATABASE_VERSION = 1;

     private static final String TABLE_NAME = "schedules";
     private static final String COLUMN_ID = "_id";
     private static final String COLUMN_NAME = "task_name";
     private static final String COLUMN_DESCRIPTION = "task_desc";
     private static final DateFormat COLUMN_DATE = new SimpleDateFormat("MM-dd-yyyy");
     private static final DateFormat COLUMN_TIME = new SimpleDateFormat("HH:mm:ss");
     private static final String COLUMN_COLOR = "task_color";
     private static final String COLUMN_IMAGE = "task_image";



    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_NAME +
                " (" + COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_NAME + " TEXT, " +
                COLUMN_DESCRIPTION + " TEXT, " +
                COLUMN_DATE + " TEXT, " +
                COLUMN_TIME + " TEXT, " +
                COLUMN_COLOR + " INTEGER, " +
                COLUMN_IMAGE + " TEXT);";
        db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);

    }

    void addSched(String Name, String Description, String Date, Integer Time, Integer Color, String Image) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_NAME, Name);
        cv.put(COLUMN_DESCRIPTION, Description);
        cv.put(String.valueOf(COLUMN_DATE), Date);
        cv.put(String.valueOf(COLUMN_TIME), Time);
        cv.put(COLUMN_COLOR, Color);
        cv.put(COLUMN_IMAGE, Image);

        long result = db.insert(TABLE_NAME, null, cv);
        if(result == -1) {
            Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "Added Successfully!", Toast.LENGTH_SHORT).show();
        }
    }
}

AddTask类

package com.ablsv.vremia;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;

import java.text.DateFormat;
import java.util.Calendar;

import yuku.ambilwarna.AmbilWarnaDialog;

public class AddTask extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener, View.OnClickListener {

    EditText taskNameInput, descInput;
    TextView datepick, timepick, colorpick, colorprev;
    int DefColor;
    ImageView imageToUpload;
    Button bSaveTask;
    private static final int RESULT_LOAD_IMAGE = 1;

    @SuppressLint("CutPasteId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_task);

        DefColor = ContextCompat.getColor(AddTask.this, R.color.white);
        ImageView cancelbtn = findViewById(R.id.cancel);
        colorpick = findViewById(R.id.colorpick);
        datepick = findViewById(R.id.datepick);
        timepick = findViewById(R.id.timepick);
        Button taskBtn = findViewById(R.id.bSaveTask);

        colorpick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openColorPicker();
            }
        });
        timepick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment tpicker = new TimePickerFragment();
                tpicker.show(getSupportFragmentManager(), "Time picker");
            }
        });

        datepick.setOnClickListener(view -> {
            DatePickerFragment dpick = new DatePickerFragment();
            dpick.show(getSupportFragmentManager(), "date picker");
        });

        cancelbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        EditText Name_input, Desc_input;
        TextView Date_input, Time_input, Color_input;
        ImageView Image_input;
        Name_input = findViewById(R.id.taskNameInput);
        Desc_input = findViewById(R.id.descInput);
        Date_input = findViewById(R.id.datepick);
        Time_input = findViewById(R.id.timepick);
        Color_input = findViewById(R.id.colorpick);
        Image_input = findViewById(R.id.imageToUpload);

        taskBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatabaseHelper Db = new DatabaseHelper(AddTask.this);
                    Db.addSched(Name_input.getText().toString().trim(),
                        Desc_input.getText().toString().trim(),
                        Date_input.getText().toString().trim(),
                        Integer.valueOf(Time_input.getText().toString().trim()),
                            Integer.valueOf(Color_input.getText().toString().trim()),
                        String.valueOf(Image_input.getImageAlpha()));
            }
        });

        imageToUpload = findViewById(R.id.imageToUpload);

        bSaveTask = findViewById(R.id.bSaveTask);

        imageToUpload.setOnClickListener(this);
        bSaveTask.setOnClickListener(this);

    }

    @Override
    public void onDateSet(DatePicker datePicker, int year, int month, int dayofmonth) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, dayofmonth);
        String cdatestr = DateFormat.getDateInstance().format(c.getTime());
        datepick.setText(cdatestr);
    }

    @Override
    public void onTimeSet(TimePicker timePicker, int hour, int minute) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
       timepick.setText(hour +":"+ minute);

    }
    public void openColorPicker()
    {
        AmbilWarnaDialog colorpicker = new AmbilWarnaDialog(this, DefColor, new AmbilWarnaDialog.OnAmbilWarnaListener() {
            @Override
            public void onCancel(AmbilWarnaDialog dialog) {

            }

            @Override
            public void onOk(AmbilWarnaDialog dialog, int color) {
                String colorhexed = toHex(color);
                colorpick.setText(colorhexed);
                colorprev = findViewById(R.id.colorpreview);
                int coldr = Color.parseColor("#"+colorhexed);
                colorprev.setBackgroundColor(coldr);
                colorpick.setText(colorhexed);

            }
        });
        colorpicker.show();
    }

    public static String toHex(int i)
    {
        long unsignedDecimal = i & 0xFFFFFFFFL;
        String hexa = Long.toHexString(unsignedDecimal);
        hexa.length();
        return hexa.toUpperCase();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageToUpload:
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
                break;
            case R.id.bSaveTask:

                break;

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            imageToUpload.setImageURI(selectedImage);
        }
    }
//end of AddTask class
}

DatePickerFragment类

package com.ablsv.vremia;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import java.util.Calendar;

public class DatePickerFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar calen = Calendar.getInstance();
        int year = calen.get(Calendar.YEAR);
        int month = calen.get(Calendar.MONTH);
        int dayOfMonth = calen.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener)getActivity(), year, month, dayOfMonth);
    }
}

TimePickerFragment类

package com.ablsv.vremia;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import java.util.Calendar;

public class TimePickerFragment extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar calen = Calendar.getInstance();
        int hour = calen.get(Calendar.HOUR_OF_DAY);
        int minute = calen.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener)getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity()));
    }
}

This is how i envisioned my app would look likeWhat i want it to do once the task/schedule is pressed

3df52oht

3df52oht1#

日期、时间和颜色都可以转换为整数。搜索一些解析器,如DateFormat。

相关问题