Android NotePad App-创建新笔记并保存时,我所做的下一次更改不会保存,直到关闭笔记并再次打开

时间:2019-03-08 21:52:49

标签: android

我是Android新手。 我正在做一个记事本应用程序,将笔记存储在数据库中。 问题是当我创建一个新笔记并保存它时(单击“保存”按钮,而未完成活动),直到关闭笔记并再次将其打开后,我所做的下一个更改才会保存。该问题仅在我创建新笔记时出现。由于创建了它,然后关闭便笺并再次打开它,因此我可以进行更改并保存它们而不会出现问题。 我有这个问题,也不知道发生了什么。

这是代码:

EditNoteActivity类

public class EditNoteActivity extends Atividade {
    private EditText inputNote;
    private NotesDao dao;
    private Note temp;
    public static final String NOTE_EXTRA_Key = "note_id";

@Override
protected void onCreate(Bundle savedInstanceState) {

    setTheme(MainActivity.getThemeId());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edite_note);
    Toolbar toolbar = findViewById(R.id.edit_toolbar);
    toolbar.setTitle(R.string.app_name);
    setSupportActionBar(toolbar);

    inputNote = findViewById(R.id.input_note);
    dao = NotesDB.getInstance(this).notesDao();
    if (getIntent().getExtras() != null) {
        int id = getIntent().getExtras().getInt(NOTE_EXTRA_Key, 0);
        temp = dao.getNoteById(id);
        inputNote.setText(temp.getNoteText());
    } else inputNote.setFocusable(true);

}

private void onSaveNote() {
    String text = inputNote.getText().toString();
    if (!text.isEmpty()) {
        long date = new Date().getTime(); // get  system time
        // if  exist update els crete new
        if (temp == null) {
            temp = new Note(text, date, 0);
            dao.insertNote(temp); // create new note and inserted to database
        } else {
            temp.setNoteText(text);
            temp.setNoteDate(date);
            dao.updateNote(temp);
        }
        Toast.makeText(this, getString(R.string.notaSalva), Toast.LENGTH_SHORT).show();
    } else
        Toast.makeText(this, getString(R.string.introduzTexto), Toast.LENGTH_SHORT).show();

}


@Override
public void onBackPressed() {
    onSaveNote();
    finish(); // return to the MainActivity
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.save_note) {
        onSaveNote();
    }
    return super.onOptionsItemSelected(item);
}

笔记班级

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;

@Entity(tableName = "notes")
public class Note {
    @PrimaryKey(autoGenerate = true)
    private int id; // default value
    @ColumnInfo(name = "text")
    private String noteText;
    @ColumnInfo(name = "date")
    private long noteDate;

@Ignore
private boolean checked = false;

@ColumnInfo(name = "n_enc")
private int num_enc;

public Note() {
}

public Note(String noteText, long noteDate, int num_enc) {
    this.noteText = noteText;
    this.noteDate = noteDate;
    this.num_enc = num_enc;
}

这是数据库连接 NotesDB类

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;

@Database(entities = Note.class, version = 1)
public abstract class NotesDB extends RoomDatabase {
    public abstract NotesDao notesDao();

  public static final String DATABSE_NAME = "notesDb";
  private static NotesDB instance;

public static NotesDB getInstance(Context context) {
    if (instance == null)
        instance = Room.databaseBuilder(context, NotesDB.class, DATABSE_NAME)
                .allowMainThreadQueries()
                .build();
    return instance;
}

}

NotesDao界面

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;

import java.util.List;

@Dao
public interface NotesDao {
/**
 * Insert and save note to Database
 *
 * @param note
 */
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertNote(Note note);

/**
 * Delete note
 *
 * @param note that will be delete
 */
@Delete
void deleteNote(Note... note);

/**
 * Update note
 *
 * @param note the note that will be update
 */
@Update
void updateNote(Note note);

/**
 * List All Notes From Database
 *
 * @return list of Notes
 */
@Query("SELECT * FROM notes")
List<Note> getNotes();

/**
 * @param noteId note id
 * @return Note
 */
@Query("SELECT * FROM notes WHERE id = :noteId")
Note getNoteById(int noteId);

/**
 * Delete Note by Id from DataBase
 *
 * @param noteId
 */
@Query("DELETE FROM notes WHERE id = :noteId")
void deleteNoteById(int noteId);

}

MainActivity(我看到笔记的地方)

public class MainActivity extends Atividade implements NoteEventListener, Drawer.OnDrawerItemClickListener {
private RecyclerView recyclerView;
private ArrayList<Note> notes;
private NotesAdapter adapter;
private NotesDao dao;
private MainActionModeCallback actionModeCallback;
private int chackedCount = 0;
private FloatingActionButton fab;
private SharedPreferences settings;
public static final String THEME_Key = "app_theme";
public static final String APP_PREFERENCES="cripd_settings";
private static int theme;
private static MainActivity INSTANCE;

@Override
protected void onCreate(Bundle savedInstanceState) {
    INSTANCE = this;
    settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
    theme = settings.getInt(THEME_Key, R.style.AppTheme);
    setTheme(theme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setTitle(R.string.app_name);
    setSupportActionBar(toolbar);

    setupNavigation(savedInstanceState, toolbar);
    // init recyclerView
    recyclerView = findViewById(R.id.notes_list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    // init fab Button
    fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onAddNewNote();
        }
    });

    dao = NotesDB.getInstance(this).notesDao();
}


 private void loadNotes() {
    this.notes = new ArrayList<>();
    List<Note> list = dao.getNotes();// get All notes from DataBase
    this.notes.addAll(list);
    this.adapter = new NotesAdapter(this, this.notes);
    // set listener to adapter
    this.adapter.setListener(this);
    this.recyclerView.setAdapter(adapter);
    showEmptyView();

    swipeToDeleteHelper.attachToRecyclerView(recyclerView);
}

private void onAddNewNote() {
    startActivity(new Intent(this, EditNoteActivity.class));
}

@Override
public void onNoteClick(Note note) {
    Intent edit = new Intent(this, EditNoteActivity.class);
    edit.putExtra(NOTE_EXTRA_Key, note.getId());
    startActivity(edit);
}

请问有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

将您的域名insertNote更改为

@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertNote(Note note);

这将返回它刚刚插入的项目的主键。

然后使用您的onSave方法:

    if (temp == null) {
        temp = new Note(text, date, 0);
        long id = dao.insertNote(temp); // create new note and inserted to database
        temp.setId(id);
    } else {
        temp.setNoteText(text);
        temp.setNoteDate(date);
        dao.updateNote(temp);
    }

房间不更新自动生成的ID。更新使用主键更新值。因此,一旦您设置了ID,它就会起作用。