首页 > 解决方案 > 视图不想更新

问题描述

我在更新我的视图时遇到了问题,该视图会更改 MainActivity 中的颜色。我单击cardview,输入“编辑注释”并更改颜色-一切正常,但是当我返回查看所有注释时,颜色没有改变,但是当我关闭应用程序并启动它时-颜色已经改变。我无法弄清楚这种行为有什么问题

主活动:onActivityResult

    if(requestCode == ADD_NOTE_REQUEST && resultCode == RESULT_OK) {
        String title = data.getStringExtra(AddEditNoteeActivity.EXTRA_TITLE);
        String text = data.getStringExtra(AddEditNoteeActivity.EXTRA_TEXT);
        String selectedColor = data.getStringExtra(AddEditNoteeActivity.EXTRA_VIEW);

        Notee notee = new Notee(title, text, selectedColor);
        noteeViewModel.insert(notee);

        Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();

    } else if(requestCode == EDIT_NOTE_REQUEST && resultCode == RESULT_OK) {
        int id = data.getIntExtra(AddEditNoteeActivity.EXTRA_ID, -1);

        if(id == -1){
            Toast.makeText(this, "Note can't be updated", Toast.LENGTH_SHORT).show();
            return;
        }
        String title = data.getStringExtra(AddEditNoteeActivity.EXTRA_TITLE);
        String text = data.getStringExtra(AddEditNoteeActivity.EXTRA_TEXT);
        String selectedColor = data.getStringExtra(AddEditNoteeActivity.EXTRA_VIEW);

        Notee notee = new Notee(title, text, selectedColor);
        
        notee.setId(id);
        noteeViewModel.update(notee);
        
        Toast.makeText(this, "Note updated", Toast.LENGTH_SHORT).show();

    } else {
            Toast.makeText(this, "Note not saved    ", Toast.LENGTH_SHORT).show();
        }
    }

编辑笔记活动:保存笔记

    String title = editTextTitle.getText().toString();
    String text = editText.getText().toString();
    String selectedColor = selectedNoteeColor;


    if(title.trim().isEmpty() || text.trim().isEmpty()){
        Toast.makeText(this, "Please make a notes", Toast.LENGTH_SHORT).show();
        return;
    }

    Intent data = new Intent();
    data.putExtra(EXTRA_TITLE, title);
    data.putExtra(EXTRA_TEXT, text);
    data.putExtra(EXTRA_VIEW, selectedColor);

    int id = getIntent().getIntExtra(EXTRA_ID, -1);
    if (id != -1) {
        data.putExtra(EXTRA_ID, id);
    }

    setResult(RESULT_OK, data);
    finish();
}

注意存储库

public class NoteeRepository {

private NoteeDao noteeDao;
private LiveData<List<Notee>> allNotes;


public NoteeRepository(Application application){
    NoteeDatabase database = NoteeDatabase.getInstance(application);
    noteeDao = database.noteeDao();
    allNotes = noteeDao.getAllNotes();
}

public void insert(Notee notee){

    new InsertNoteeAsynTask(noteeDao).execute(notee);

}

public void delete(Notee notee){
    new DeleteNoteeAsynTask(noteeDao).execute(notee);
}

public void update(Notee notee){
    new UpdateNoteeAsynTask(noteeDao).execute(notee);
}

public void deleteAllNotees(){
    new DeleteAllNoteesAsynTask(noteeDao).execute();
}

public LiveData<List<Notee>> getAllNotes(){
    return allNotes;
}

private static class InsertNoteeAsynTask extends AsyncTask<Notee, Void, Void>{

    private NoteeDao noteeDao;

    private InsertNoteeAsynTask(NoteeDao noteeDao){
        this.noteeDao = noteeDao;
    }

    @Override
    protected Void doInBackground(Notee...notees){

        noteeDao.insert(notees[0]);
        return null;
    }
}

private static class DeleteNoteeAsynTask extends AsyncTask<Notee, Void, Void>{

    private NoteeDao noteeDao;

    private DeleteNoteeAsynTask(NoteeDao noteeDao){
        this.noteeDao = noteeDao;
    }

    @Override
    protected Void doInBackground(Notee...notees){
        noteeDao.delete(notees[0]);
        return null;
    }
}

private static class UpdateNoteeAsynTask extends AsyncTask<Notee, Void, Void>{

    private NoteeDao noteeDao;

    private UpdateNoteeAsynTask(NoteeDao noteeDao){
        this.noteeDao = noteeDao;
    }

    @Override
    protected Void doInBackground(Notee...notees){
        noteeDao.insert(notees[0]);
        return null;
    }
}

private static class DeleteAllNoteesAsynTask extends AsyncTask<Notee, Void, Void>{

    private NoteeDao noteeDao;

    private DeleteAllNoteesAsynTask(NoteeDao noteeDao){
        this.noteeDao = noteeDao;
    }

    @Override
    protected Void doInBackground(Notee...notees){
        noteeDao.deleteAllNote();
        return null;
    }
}

}

@Entity (tableName = "note_table") 公共类 Notee {

@PrimaryKey(autoGenerate = true)
private int id;

private String title;
private String text;
private String image;


public Notee(String title, String text, String image) {
    this.title = title;
    this.text = text;
    this.image = image;

}

public void setId(int id) {
    this.id = id;
}

public int getId() {
    return id;
}

public String getTitle() {
    return title;
}

public String getText() {
    return text;
}

public String getImage() {
    return image;
}

}

@Override public void onBindViewHolder(@NonNull NoteeHolder holder, int position) {

    Notee currentNotee = getItem(position);
    holder.textViewText.setText(currentNotee.getText());
    holder.textViewTitle.setText(currentNotee.getTitle());
    holder.viewColor.setBackground(new ColorCircleDrawable(Color.parseColor(currentNotee.getImage())));
}


// Get the position of the notees

public Notee getNoteAt(int position){
    return getItem(position);
}




class NoteeHolder extends RecyclerView.ViewHolder {

    private TextView textViewTitle;
    private TextView textViewText;
    private View viewColor;

    public NoteeHolder(@NonNull View itemView) {
        super(itemView);

        textViewTitle = itemView.findViewById(R.id.title);
        textViewText = itemView.findViewById(R.id.text);
        viewColor = itemView.findViewById(R.id.color);

        itemView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                int position = getAdapterPosition();
                if(listener != null && position != RecyclerView.NO_POSITION) {
                    listener.OnItemClick(getItem(position));
                }
            }
        });

    }

来自 NoteeViewModel

  public class NoteeViewModel extends AndroidViewModel {

    private NoteeRepository repository;
    private LiveData<List<Notee>> allNotes;

    public NoteeViewModel(@NonNull Application application) {
        super(application);
        repository = new NoteeRepository(application);
        allNotes = repository.getAllNotes();
    }

    public void insert(Notee notee){
        repository.insert(notee);
    }

    public void delete(Notee notee){
        repository.delete(notee);
    }

    public void update(Notee notee){
        repository.update(notee);
    }

    public void deleteAllNote(){
        repository.deleteAllNotees();
    }

    public LiveData<List<Notee>> getAllNotes() {
        return allNotes;
    }
}

从 MainActivity onCreate

noteeViewModel = ViewModelProviders.of(this).get(NoteeViewModel.class);
        noteeViewModel.getAllNotes().observe(this, new Observer<List<Notee>>() {

            @Override
            public void onChanged(@NonNull List<Notee> notees){
                adapter.submitList(notees);
            }
        });

标签: android

解决方案


您发布的代码对此没问题,但问题出在noteeViewModel的某个地方,可能......检查您是否在某处使用了removeSource

创建新笔记时一切正常吗?你只有颜色有问题吗?如果标题和文字刷新了,颜色没有了,那就是RecyclerView有问题...

**而不是 onActivityResult 最好为 AddEditNoteeActivity 创建一个 AdEditViewModel(用于使用捆绑编辑发送便笺 ID),创建或编辑加载的便笺(由 id 加载)并保存它...当您返回 MainActivity 房间时,它将如果您没有取消订阅,请刷新笔记

编辑:

我对你的问题很好奇,所以我尝试了你的代码,插入和更新一切正常

使用您的代码,我使用了:

分级文件

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation  "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor  "android.arch.persistence.room:compiler:1.1.1"

@Dao
public interface NoteeDao {

    @Query("SELECT * FROM note_table ORDER BY id")
    public LiveData<List<Notee>> readAll();  
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertList(List<Notee> notees);
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(Notee... notees);
    @Update
    void update(Notee... notees);
    @Delete
    void delete(Notee notee);

}

数据库

public static NoteeDatabase getInstance(final Context context) {
        if (sInstance == null) {
            synchronized (NoteeDatabase.class) {
                if (sInstance == null) {
                    sInstance = buildDatabase(context.getApplicationContext());
                    sInstance.updateDatabaseCreated(context.getApplicationContext());
                }
            }
        }
        return sInstance;
    }

检查这些东西,或者您可以尝试重建应用程序,使现金无效... ViewModelProviders.of(this).get(NoteeViewModel.class) 已被弃用,但它有效...搜索有关此的更多详细信息


推荐阅读