您好,我正在制作一个简单的note应用程序,使用一个sqlite数据库,使用一个自定义的arraylist适配器,在这里用户可以保存一个带有标题、描述性文本和日期的note。一切正常,但我希望只有标题不在数据库中时,用户才能保存新的注释。我该怎么做?
这是编辑说明

public class Edit_notes extends AppCompatActivity {

    private DBOpenHelper dbop;
    private SQLiteDatabase sdb;
    private EditText title_text;
    private EditText note_text;


    public boolean SaveNote(){

        String note_title_string = title_text.getText().toString();
        String note_text_string = note_text.getText().toString();

        if (!note_title_string.isEmpty()){
            if(!note_text_string.isEmpty()) {

// Need to check if title is not in the database then insert else don't

                String date = new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + (new Date().getYear() + 1900);
                AddData(note_title_string, note_text_string, date); // Add title to the database
                Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();
                finish();
            }
            else {
                Toast.makeText(this, "Note text cannot be empty", Toast.LENGTH_SHORT).show();
            }

        }
        else{
            Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show();
        }

        return true;
    }

    public void AddData(String title_entry, String text_entry, String date){

        dbop = new DBOpenHelper(this);
        sdb = dbop.getWritableDatabase();

        ContentValues cv = new ContentValues();
        cv.put("TITLE", title_entry);
        cv.put("TEXT", text_entry);
        cv.put("DATE", date);

        sdb.insert("note_table", null, cv);
    }

}

sqlite数据库.java:
public class DBOpenHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "notes.db";
public static final String TABLE_NAME = "note_table";
public static final String ID_COLUMN = "ID";
public static final String TITLE_COLUMN = "TITLE";
public static final String TEXT_COLUMN = "TEXT";
public static final String DATE_COLUMN = "DATE";

SQLiteDatabase db = this.getWritableDatabase();


public DBOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, 5);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME
            + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT, " + " TEXT TEXT, " + " DATE STRING)";
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table note_table");
    onCreate(db);
}

}
我想没有必要提供mainActivity.java

最佳答案

将表格创建更改为:

String createTable = "CREATE TABLE " + TABLE_NAME
        + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT UNIQUE, " + " TEXT TEXT, " + " DATE STRING)";

卸载应用程序,或删除应用程序的数据,或增加数据库版本号并重新运行该应用程序。不会添加行唯一约束冲突(同一标题)(insert方法有效使用INSERT OR IGNORE)。

关于java - Android Studio SQLite是否在数据库中保存标题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55231397/

10-11 22:32
查看更多