Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android RecyclerView项目删除,但当我移动到其他活动时返回,然后返回_Android_Android Recyclerview - Fatal编程技术网

Android RecyclerView项目删除,但当我移动到其他活动时返回,然后返回

Android RecyclerView项目删除,但当我移动到其他活动时返回,然后返回,android,android-recyclerview,Android,Android Recyclerview,我在我的recyclerView中添加了一些新代码,在向左或向右滑动时删除该项目,但当我移动到其他活动,然后返回到我的recyclerView活动时,这些项目会重新出现。以下是我的MainActivity(称为TestGroceryList)的代码: 公共类TestGroceryList扩展了AppCompative活动{ 私有WordViewModel mWordViewModel; 公共静态最终int NEW\u WORD\u ACTIVITY\u REQUEST\u CODE=1; @凌驾

我在我的recyclerView中添加了一些新代码,在向左或向右滑动时删除该项目,但当我移动到其他活动,然后返回到我的recyclerView活动时,这些项目会重新出现。以下是我的MainActivity(称为TestGroceryList)的代码:

公共类TestGroceryList扩展了AppCompative活动{
私有WordViewModel mWordViewModel;
公共静态最终int NEW\u WORD\u ACTIVITY\u REQUEST\u CODE=1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u test\u screery\u list);
RecyclerView RecyclerView=findViewById(R.id.RecyclerView);
最终WordListAdapter=新WordListAdapter(此);
recyclerView.setAdapter(适配器);
recyclerView.setLayoutManager(新的LinearLayoutManager(本));
mWordViewModel=newViewModelProvider(this.get)(WordViewModel.class);
mWordViewModel.getAllWords().observe(这个,新的观察者(){
@凌驾
公共void onChanged(@Nullable final List words){
//更新适配器中单词的缓存副本。
adapter.setWords(单词);
}
});
新建ItemTouchHelper(新建ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT){
@凌驾
公共布尔onMove(@NonNull RecyclerView RecyclerView,@NonNull RecyclerView.ViewHolder ViewHolder,@NonNull RecyclerView.ViewHolder target){
返回false;
}
@凌驾
公共void onsweed(@NonNull RecyclerView.ViewHolder ViewHolder,int-direction){
delete(adapter.getWordAt(viewHolder.getAdapterPosition());
Toast.makeText(TestGroceryList.this,“项目已删除!”,Toast.LENGTH\u SHORT.show();
}
}).attachToRecyclerView(recyclerView);
FloatingActionButton fab=findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Intent Intent=newintent(TestGroceryList.this,NewWordActivity.class);
startActivityForResult(意图、新词、活动、请求、代码);
}
});
}
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==NEW\u WORD\u ACTIVITY\u REQUEST\u CODE&&resultCode==RESULT\u OK){
Word=newword(data.getStringExtra(NewWordActivity.EXTRA_REPLY));
mWordViewModel.insert(word);
}否则{
Toast.makeText(
getApplicationContext(),
R.string.empty\u未保存,
Toast.LENGTH_LONG).show();
}
}
下面是我的适配器的代码:

public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {


    static class WordViewHolder extends RecyclerView.ViewHolder {
        private final TextView wordItemView;

        private WordViewHolder(View itemView) {
            super(itemView);
            wordItemView = itemView.findViewById(R.id.textView);
        }
    }

    private final LayoutInflater mInflater;
    private List<Word> mWords; // Cached copy of words

    WordListAdapter(Context context) { mInflater = LayoutInflater.from(context); }

    @Override
    public WordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.recycler_item, parent, false);
        return new WordViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(WordViewHolder holder, int position) {
        if (mWords != null) {
            Word current = mWords.get(position);
            holder.wordItemView.setText(current.getWord());
        } else {
            // Covers the case of data not being ready yet.
            holder.wordItemView.setText("No thecookbookerapp.com.Word");
        }
    }

    void setWords(List<Word> words){
        mWords = words;
        notifyDataSetChanged();
    }

    public Word getWordAt(int position){
        return mWords.get(position);
    }


    // getItemCount() is called many times, and when it is first called,
    // mWords has not been updated (means initially, it's null, and we can't return null).
    @Override
    public int getItemCount() {
        if (mWords != null)
            return mWords.size();
        else return 0;
    }
}
公共类WordListAdapter扩展了RecyclerView.Adapter{
静态类WordViewHolder扩展了RecyclerView.ViewHolder{
私有最终文本视图wordItemView;
私有WordViewHolder(查看项目视图){
超级(项目视图);
wordItemView=itemView.findViewById(R.id.textView);
}
}
私人最终布局平面图;
私有列表mWords;//缓存的单词副本
WordListAdapter(上下文){mInflater=LayoutInflater.from(上下文);}
@凌驾
public WordViewHolder onCreateViewHolder(视图组父级,int-viewType){
View itemView=mInflater.inflate(R.layout.recycler\u项目,父项,false);
返回新的WordViewHolder(itemView);
}
@凌驾
BindViewHolder上的公共无效(WordViewHolder,int位置){
if(mWords!=null){
单词current=mWords.get(位置);
holder.wordItemView.setText(current.getWord());
}否则{
//涵盖数据尚未准备就绪的情况。
holder.wordItemView.setText(“No thecookbookerapp.com.Word”);
}
}
无效设置字(列出字){
MWORD=单词;
notifyDataSetChanged();
}
公共单词getWordAt(int位置){
返回mWords.get(位置);
}
//getItemCount()被多次调用,第一次调用时,
//mWords尚未更新(最初表示为null,我们不能返回null)。
@凌驾
public int getItemCount(){
if(mWords!=null)
返回mWords.size();
否则返回0;
}
}
以下是我的WordViewModel:

package thecookbookerapp.com;

import android.app.Application;
import android.content.Intent;
import android.widget.Toast;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import java.util.List;

import static android.app.Activity.RESULT_OK;
import static 
thecookbookerapp.com.TestGroceryList.NEW_WORD_ACTIVITY_REQUEST_CODE;

public class WordViewModel extends AndroidViewModel {

private WordRepository mRepository;

private LiveData<List<Word>> mAllWords;

public WordViewModel (Application application) {
    super(application);
    mRepository = new WordRepository(application);
    mAllWords = mRepository.getAllWords();
}

public static void delete(Word wordAt) {

}

LiveData<List<Word>> getAllWords() { return mAllWords; }

public void insert(Word word) { mRepository.insert(word); }

}
打包cookbookerapp.com;
导入android.app.Application;
导入android.content.Intent;
导入android.widget.Toast;
导入androidx.lifecycle.AndroidViewModel;
导入androidx.lifecycle.LiveData;
导入java.util.List;
导入静态android.app.Activity.RESULT\u确定;
导入静态
cookbookerapp.com.TestGroceryList.NEW\u WORD\u ACTIVITY\u REQUEST\u CODE;
公共类WordViewModel扩展了AndroidViewModel{
私有词存储库;
私有LiveData;
公共WordViewModel(应用程序){
超级(应用);
mRepository=新单词库(应用程序);
mAllWords=mRepository.getAllWords();
}
公共静态无效删除(Word wordAt){
}
LiveData getAllWords(){return mAllWords;}
公共空白插入(Word){mRepository.insert(Word);}
}
这是我的WordRepository:

class WordRepository {

private WordDao mWordDao;
private LiveData<List<Word>> mAllWords;

// Note that in order to unit test the WordRepository, you have to remove the Application
// dependency. This adds complexity and much more code, and this sample is not about testing.
// See the BasicSample in the android-architecture-components repository at
// https://github.com/googlesamples
WordRepository(Application application) {
    WordRoomDatabase db = WordRoomDatabase.getDatabase(application);
    mWordDao = db.wordDao();
    mAllWords = mWordDao.getAlphabetizedWords();
}

// Room executes all queries on a separate thread.
// Observed LiveData will notify the observer when the data has changed.
LiveData<List<Word>> getAllWords() {
    return mAllWords;
}

// You must call this on a non-UI thread or your app will throw an exception. Room ensures
// that you're not doing any long running operations on the main thread, blocking the UI.
void insert(Word word) {
    WordRoomDatabase.databaseWriteExecutor.execute(() -> {
        mWordDao.insert(word);
    });
}
}
classwordrepository{
私人WordDao mWordDao;
私有LiveData;
//请注意,为了对WordRepository进行单元测试,必须删除应用程序
//这增加了复杂性和更多的代码,本示例与测试无关。
//请参阅android架构组件存储库中的BasicSample
// https://github.com/googlesamples
WordRepository(应用程序){
WordRoomDatabase db=WordRoomDatabase.getDatabase(ap
class WordRepository {

private WordDao mWordDao;
private LiveData<List<Word>> mAllWords;

// Note that in order to unit test the WordRepository, you have to remove the Application
// dependency. This adds complexity and much more code, and this sample is not about testing.
// See the BasicSample in the android-architecture-components repository at
// https://github.com/googlesamples
WordRepository(Application application) {
    WordRoomDatabase db = WordRoomDatabase.getDatabase(application);
    mWordDao = db.wordDao();
    mAllWords = mWordDao.getAlphabetizedWords();
}

// Room executes all queries on a separate thread.
// Observed LiveData will notify the observer when the data has changed.
LiveData<List<Word>> getAllWords() {
    return mAllWords;
}

// You must call this on a non-UI thread or your app will throw an exception. Room ensures
// that you're not doing any long running operations on the main thread, blocking the UI.
void insert(Word word) {
    WordRoomDatabase.databaseWriteExecutor.execute(() -> {
        mWordDao.insert(word);
    });
}
}
import androidx.room.Query;

import java.util.List;

@Dao
public interface WordDao {

// allowing the insert of the same word multiple times by passing a
// conflict resolution strategy
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(Word word);

@Query("DELETE FROM word_table")
void deleteAll();

@Query("SELECT * from word_table ORDER BY word ASC")
LiveData<List<Word>> getAlphabetizedWords();

@Delete
void delete(Word word);
public void delete(Word word) {
    WordRoomDatabase.databaseWriteExecutor.execute(() -> {
        mWordDao.delete(word);
    });
}
public void delete(Word word) {
    mRepository.delete(word); 
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
    mWordViewModel.delete(adapter.getWordAt(viewHolder.getAdapterPosition()));
    Toast.makeText(TestGroceryList.this, "Item Deleted!", Toast.LENGTH_SHORT).show();

}