我在我的recyclerView中添加了一些新代码,当向左或向右滑动时会删除该项目,但当我移动到另一个活动,然后返回到我的recyclerView活动时,这些项目会重新出现。下面是我的MainActivity(名为TestGroceryList)的代码:
public class TestGroceryList extends AppCompatActivity {
private WordViewModel mWordViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_grocery_list);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final WordListAdapter adapter = new WordListAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mWordViewModel = new ViewModelProvider(this).get(WordViewModel.class);
mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
@Override
public void onChanged(@Nullable final List<Word> words) {
// Update the cached copy of the words in the adapter.
adapter.setWords(words);
}
});
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
WordViewModel.delete(adapter.getWordAt(viewHolder.getAdapterPosition()));
Toast.makeText(TestGroceryList.this, "Item Deleted!", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(TestGroceryList.this, NewWordActivity.class);
startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
Word word = new Word(data.getStringExtra(NewWordActivity.EXTRA_REPLY));
mWordViewModel.insert(word);
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}下面是我的Adapter的代码:
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;
}
}这是我的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); }
}这是我的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);
});
}
}这是我的WordDao:
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);}
以下是我的问题的视频:Link
谁能帮帮我?谢谢
发布于 2020-08-03 04:50:18
当你滑动一个项目时,你调用了WordViewModel.delete();但实际上你需要在你的WordViewModel中实现这个方法,因为你把它留空了;
在Repository的add below方法中
public void delete(Word word) {
WordRoomDatabase.databaseWriteExecutor.execute(() -> {
mWordDao.delete(word);
});
}在ViewModel中修改delete方法为
public void delete(Word word) {
mRepository.delete(word);
}并修改ItemTouchHelper onSwipe()以使用ViewModel非静态方法
@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();
}https://stackoverflow.com/questions/63181854
复制相似问题