使用SharedPreferences在Android中的SQLite数据库中存储主键值

时间:2014-12-18 06:57:17

标签: android sqlite

我有一个表格,询问名称,性别等值。这些值存储在一个表中,主表字段ID不是由用户输入的。每次使用SharedPreferences保存新记录时,我必须输入它的值。我该怎么做?

这是我的班级档案:

saveBtn = (Button) view.findViewById(R.id.save);
saveBtn.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        String name             = nameEdt.getText().toString().trim();
        String trainingTypes    = trainingTypesSpn.toString().trim();
        String trainerProfile   = trainerProfileSpn.toString().trim();
        String description      = descriptionEdt.toString().trim();
        String plannedBudget    = plannedBudgetNp.toString().trim();
        String startDt          = startDtEdt.toString().trim();
        String endDt            = endDtEdt.toString().trim();

        TrainingDetailsDTO dto = new TrainingDetailsDTO();

        dto.setName(name);
        dto.setTrainingTypes(trainingTypes);
        dto.setTrainerProfile(trainerProfile);
        dto.setDescription(description);
        dto.setPlannedBudget(plannedBudget);
        dto.setStartDt(startDt);
        dto.setEndDt(endDt);

        SQLiteDatabase database = DBHandler.getInstance(mActivity).getDBObject(1);
        boolean isInsert = TrainingDetailsDAO.getInstance().insert(dto, database);

        if (isInsert)
        {

            Toast.makeText(mActivity, "Inserted Successfully", Toast.LENGTH_SHORT).show();
            mActivity.popFragments();
            mActivity.pushFragments(Constants.TAB_HOUSE, new HouseConstructionTrack(), false, false);
        }
        else
        {
            Toast.makeText(mActivity, "Insert Problem", Toast.LENGTH_SHORT).show();
        }

        mActivity.popFragments();
    }
});

这是我在DAO类中的插入方法:

public boolean insert(DTO dtoObject, SQLiteDatabase dbObject)
{
    TrainingDetailsDTO dto = (TrainingDetailsDTO) dtoObject;

    ContentValues cValues = new ContentValues();
    cValues.put("TrainingDetailsId", "TR001"); 
    cValues.put("name"          ,   dto.getName());
    cValues.put("trainingTypes" ,   dto.getTrainingTypes());
    cValues.put("trainerProfile",   dto.getTrainerProfile());
    cValues.put("description"   ,   dto.getDescription());
    cValues.put("plannedBudget" ,   dto.getPlannedBudget());
    cValues.put("startDt"       ,   dto.getStartDt());
    cValues.put("endDt"         ,   dto.getEndDt());

    dbObject.insert("TRAINING_DETAILS", null, cValues);

    return false;
}

在这里,我只能为第一条记录提供Id。如何使用SharedPreferences生成后续ID?

1 个答案:

答案 0 :(得分:1)

在Android中扩展BaseColumns。它会自动具有_ID字段,该字段会自动递增。

public static abstract class User implements BaseColumns {
    public static final String TABLE_NAME = "user";
    public static final String COLUMN_NAME_TOKEN = "token";
}