如何在Android SQLite中设置和保存日期?

时间:2013-07-10 10:47:26

标签: android android-sqlite android-datepicker

我正在尝试创建一个TaskManager我有一个setDate Button,当我点击SetDate Button时,它会在下一个Activity上传递给我,我在布局中放置了DatePicker。我正在尝试设置日期,然后使用确定按钮将该设置日期传递到数据库中。

Datepicker活动:

public class Task_Details extends Activity implements OnClickListener {

DatePicker datePicker;
private DatePicker.OnDateChangedListener dateSetListener;
Button okBtn, cancelBtn;
String setDate;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.task_details);
    datePicker = (DatePicker)findViewById(R.id.setDueDate);
    datePicker.init(datePicker.getYear(),datePicker.getMonth(), datePicker.getDayOfMonth(), dateSetListener);

okBtn = (Button)findViewById(R.id.okBtn);
    okBtn.setOnClickListener(this);
    cancelBtn = (Button)findViewById(R.id.cancelBtn);
    cancelBtn.setOnClickListener(this);
@Override
public void onClick(View v) {
    switch(v.getId()){
    case R.id.okBtn:
        String returnDate = setDate();
        db = new TodoTask_Database(getApplicationContext());  //Database call
        db.addTaskDetails(returnDate);   //Datebase method
        break;
    case R.id.cancelBtn:
        Intent intent = new Intent(getApplicationContext(), Add_Task.class);
        startActivity(intent);
        break;
    }
}
    String setDate(){
    dateSetListener = new DatePicker.OnDateChangedListener() {
        public void onDateChanged(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {

            System.out.println(+ year+"-"+ monthOfYear+"-"+ dayOfMonth);

            String Year=Integer.toString(year); 
            String Month=Integer.toString(monthOfYear); 
            String Day=Integer.toString(dayOfMonth);

            System.out.println(Year+"-"+Month+"-"+Day); 
        }
    };
    return setDate;
    }
}

我正在尝试获取日期并保存到数据库中。

5 个答案:

答案 0 :(得分:0)

你在这里遇到的问题是你试图通过设置一个回调监听器来从选择器中获得结果。

您需要做的是在findViewById之后在onCreate方法中设置监听器。

选择日期后,设置成员变量。单击“确定”后,在数据库方法中使用成员变量。

答案 1 :(得分:0)

试一试。

protected void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_myprofile);
    datePickerDialog = new DatePickerDialog(this, mDateSetListener, year,
                month, day);
String returnDate = ""+date;
}
DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
                date = new Date(year - 1900, monthOfYear, dayOfMonth);

        }

    };

答案 2 :(得分:0)

您可以这样做:

 case R.id.okBtn:
      String year = datePicker.getYear(); //and so on!
      ...
      String date = year + month + day;
      db.addToDb(date);
      break;

答案 3 :(得分:0)

请尝试使用以下代码。

package com.phone.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.phone.util.ConstantLib;

public class DBAdapter {

    private static final String TAG = "DBAdapter";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";  
        private static final String KEY_DATE = "dates";
    private static final String DATABASE_NAME = "SqlDB.db";
    private static final String DATABASE_TABLE = "tab";
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_VERSION = 1;
    private static final String TABLE_CREATE = "create table  if not exists "
            + "tab(" + "id integer primary key not null, "
            + "name text not null , " +

            "dates text not null);";

    private final Context context;

    private final DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) {
        context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(TABLE_CREATE);
            } catch (Exception e) {
                Log.i(TAG, e.toString());
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            try {
                db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
                onCreate(db);
            } catch (Exception e) {
                Log.i(TAG, e.toString());
            }
        }
    }

    // end DatabaseHelper

    // ---opens the database---
    public DBAdapter open() throws SQLException {
        try {
            db = DBHelper.getWritableDatabase();
            db.setLockingEnabled(true);// -----------------------------------
        } catch (Exception e) {
            Log.i(TAG, e.toString());
        }
        return this;
    }

    // ---closes the database---
    public void close() {
        try {
            DBHelper.close();

        } catch (Exception e) {
            Log.i(TAG, e.toString());
        }
    }

    // ---insert a remindar into the database---
    public long insertData(String id, String name, String date) {
        try {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_ID, id);
            initialValues.put(KEY_NAME, name);
            initialValues.put(KEY_DATE, date);

            return db.insert(DATABASE_TABLE, null, initialValues);
        } catch (SQLiteConstraintException e) {

        }

        catch (Exception e) {
            Log.i(TAG, e.toString());
        }

        return -1;
    }


}

答案 4 :(得分:0)

Date d = new Date();
CharSequence s  = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
Log.d("Current date and time",s.toString());