将第一个列表和最后一个列表中的特定值保存到SQLite

时间:2015-12-01 06:57:25

标签: java android sqlite listview android-listview

我有一个listView如下图所示。

enter image description here

点击提交button后,我希望第一行中的Time In和第二行中的Time Out保存到时间表中。有可能实现吗?

时间表

------------------------
| PK |Time In  |Time Out|
| -= |---------|--------|
|  1 |  9:0    | 18:0   |
|    |         |        |

1 个答案:

答案 0 :(得分:1)

您可以将时间转换为int,然后保存到sqlite,例如:

Store : 14:30  ===> 14 * 60 + 30 ===> 870

Read : 870 ===> hour= 870 / 60; minute = 870 % 60; ===> String time=hour+":"+minute;

数据库:

public class Database {

private TimesHelper mHelper;
private SQLiteDatabase mDatabase;

public Database(Context context) {

    this.mHelper = new TimesHelper(context);
    this.mDatabase = this.mHelper.getWritableDatabase();
}

public void insertTimes(int timeIn, int timeOut){

    String sql = "INSERT INTO TimeTable VALUES (?,?,?);";

    SQLiteStatement statement = this.mDatabase.compileStatement(sql);
    this.mDatabase.beginTransaction();

    statement.clearBindings();

    statement.bindString(2, timeIn);
    statement.bindLong(3, timeOut);     

    statement.execute();        

    this.mDatabase.setTransactionSuccessful();
    this.mDatabase.endTransaction();
}

public String getAllTimeTable(){

    //get a list of columns to be retrieved, we need all of them
    String[] columns = {
            "ID",
            "TimeIn",
            "TimeOut"                
    };

    Cursor cursor = this.mDatabase.query("TimeTable", columns, null, null, null, null, null);

    String result = "";

    if(cursor != null && cursor.moveToFirst()){

        do{

            int timeIn = cursor.getInt(cursor.getColumnIndex("TimeIn"));  
            int timeOut = cursor.getInt(cursor.getColumnIndex("TimeOut"));

            result = (timeIn / 60) + ":" + (timeOut % 60);
        }
        while (cursor.moveToNext());
    }

    return result;
}

private static class TimesHelper extends SQLiteOpenHelper{

    private Context mContext;
    private static final String DB_NAME= "db";
    private static final int DB_VERSION= 1;        

    private static final String CREATE_TABLE_TIME_TABLE= "CREATE TABLE TimeTable (ID INTEGER PRIMARY KEY AUTOINCREMENT,TimeIn INTEGER,TimeOut INTEGER);";


    public TimesHelper(Context context) {

        super(context, DB_NAME, null, DB_VERSION);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        try {

            db.execSQL(CREATE_TABLE_TIME_TABLE);                
        }
        catch (SQLiteException exception){

        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        try {

            db.execSQL("DROP TABLE TimeTable IF EXISTS;");
            onCreate(db);
        }
        catch (SQLiteException exception){

        }
    }
}

}