如果我想从另一个片段中添加书签,为啥我的书签单词没有保存到 sqlite 数据库?
Posted
技术标签:
【中文标题】如果我想从另一个片段中添加书签,为啥我的书签单词没有保存到 sqlite 数据库?【英文标题】:Why my bookmarked words doesn't saved to sqlite database if i want to add them from another fragment?如果我想从另一个片段中添加书签,为什么我的书签单词没有保存到 sqlite 数据库? 【发布时间】:2021-12-20 02:35:38 【问题描述】:主要问题是,当我从直接 recyclerview 添加书签代码时,它工作得非常好,但是当我将这些代码添加到另一个片段时,它只显示添加或删除书签的祝酒词,但书签中的单词没有显示最喜欢的列表。
这是我的数据库代码
public class DictionaryDB
public static final String ID = "id";
public static final String SANSKRIT = "sanskrit_word";
public static final String BANGLA = "bn_word";
public static final String STATUS = "status";
public static final String USER = "user_created";
public static final String TABLE_NAME = "sanskrit_words";
public static final String BOOKMARKED = "b";
public static final String USER_CREATED = "u";
DatabaseInitializer initializer;
public DictionaryDB(DatabaseInitializer initializer)
this.initializer = initializer;
public void addWord(String sanskritWord, String banglaWord)
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "INSERT INTO " + TABLE_NAME + " (" + SANSKRIT +
", " + BANGLA + ", " + USER + ") VALUES ('" + sanskritWord +
"', '" + banglaWord + "', '" + USER_CREATED + "') ";
db.execSQL(sql);
public List<Word> getWords(String sanskritWord)
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + SANSKRIT + " LIKE ? ";
Cursor cursor = null;
try
cursor = db.rawQuery(sql, new String[]sanskritWord + "%");
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext())
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
return wordList;
catch (SQLiteException exception)
exception.printStackTrace();
return null;
finally
if (cursor != null)
cursor.close();
//************Waka Maka Saka *****************//******************//
public List<Word> getBookmarkedWords()
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + STATUS + " = '" + BOOKMARKED + "'";
Cursor cursor = db.rawQuery(sql, null);
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext())
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
cursor.close();
db.close();
return wordList;
public void bookmark(int id)
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '"
+ BOOKMARKED + "' WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
public void deleteBookmark(int id)
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '' " +
" WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
我的回收站查看代码
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>implements Filterable
private Context context;
private List<Word> wordList;
List<Word> filwordList;
private DictionaryDB dictionaryDB;
public RecyclerViewAdapter(Context context, List<Word> itemList, DictionaryDB dictionaryDB)
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Word>(itemList);
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
// Create and return a new holder instance
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
@Override
public void onBindViewHolder(final ViewHolder holder, int position)
final Word word = wordList.get(position);
holder.msanskrit.setText(word.sanskrit);
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED))
holder.bookmark.setImageResource(R.drawable.cards_heart);
else
holder.bookmark.setImageResource(R.drawable.cards_heart_grey);
holder.bookmark.setOnClickListener(new View.OnClickListener()
public void onClick(View v)
bookMarkWord(word, holder.bookmark);
);
private void bookMarkWord(final Word word, final ImageButton bookmark)
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED))
dictionaryDB.deleteBookmark(word.id);
word.status = "";
bookmark.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(context, "Bookmark Deleted", Toast.LENGTH_SHORT).show();
else
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
bookmark.setImageResource(R.drawable.cards_heart);
Toast.makeText(context, "Bookmark Added", Toast.LENGTH_SHORT).show();
/*
public void updateEntries(List<Word> wordList)
if (wordList == null)
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Sorry!")
.setMessage("Your phone doesn't support pre-built database")
.create();
dialog.show();
else
this.wordList = wordList;
notifyDataSetChanged();
*/
@Override
public Filter getFilter()
return Searched_Filter;
private Filter Searched_Filter = new Filter()
@Override
protected FilterResults performFiltering(CharSequence constraint)
List<Word> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0)
filteredList.addAll(filwordList);
else
String filterPattern = constraint.toString().toLowerCase().trim();
for (Word item : filwordList)
if (item.getSanskrit().toLowerCase().contains(filterPattern))
filteredList.add(item);
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
@Override
protected void publishResults(CharSequence constraint, FilterResults results)
wordList.clear();
wordList.addAll((ArrayList<Word>)results.values);
notifyDataSetChanged();
;
@Override
public int getItemCount()
return wordList.size();
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
TextView msanskrit;
final ImageButton bookmark;
public ViewHolder(View itemView)
super(itemView);
itemView.setOnClickListener(this);
msanskrit = itemView.findViewById(R.id.tvSansTerm);
// mbangla = itemView.findViewById(R.id.tvBnTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
@Override
public void onClick(View view)
int position = this.getAdapterPosition();
Word word = wordList.get(position);
String sanskrit = word.getSanskrit();
String bangla = word.getBangla();
// String sources = term.getMSources();
Intent intent = new Intent(context, TermThreeDetailsActivity.class);
intent.putExtra("Rsanskrit", sanskrit);
intent.putExtra("Rbangla", bangla);
// intent.putExtra("Rsources", sources);
context.startActivity(intent);
我的 Detalis 片段代码
public class TermThreeDetailsFragment extends Fragment
private Toolbar toolbar;
TextView termTextView,descTextView;
private ImageButton imgBtn;
private DictionaryDB dictionaryDB;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View view = inflater.inflate(R.layout.show_three_details, container, false);
termTextView = view.findViewById(R.id.textvWord);
descTextView = view.findViewById(R.id.textvDesc);
imgBtn = view.findViewById(R.id.favAddBtn);
getData();
toolbar = ((Toolbar) view.findViewById(R.id.toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
WordCheck();
return view;
public void getData()
Intent intent = getActivity().getIntent();
String sanskrit = intent.getStringExtra("Rsanskrit");
String bangla = intent.getStringExtra("Rbangla");
termTextView.setText(sanskrit);
descTextView.setText(bangla);
private void WordCheck()
final Word word = new Word();
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED))
imgBtn.setImageResource(R.drawable.cards_heart);
else
imgBtn.setImageResource(R.drawable.cards_heart_grey);
imgBtn.setOnClickListener(new View.OnClickListener()
public void onClick(View v)
bookMarkWord(word, imgBtn);
);
private void bookMarkWord(final Word word, final ImageButton imgBtn)
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED))
dictionaryDB.deleteBookmark(word.id);
word.status = "";
imgBtn.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(getContext(), "Bookmark Deleted", Toast.LENGTH_SHORT).show();
else
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
imgBtn.setImageResource(R.drawable.cards_heart);
Toast.makeText(getContext(), "Bookmark Added", Toast.LENGTH_SHORT).show();
我最喜欢的片段代码
public class FavoritesFragment extends Fragment
RecyclerView rv;
private LinearLayoutManager layoutManager;
DictionaryDB dictionaryDB;
FavoriteAdapter rvFavAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View view = inflater.inflate(R.layout.favorites_fragment,container,false);
Toolbar toolbar = ((Toolbar) view.findViewById(R.id.fav_toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
List<Word> wordList = dictionaryDB.getBookmarkedWords();
rv = ((RecyclerView) view.findViewById(R.id.rvFavorites));
if (wordList.size() != 0)
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
rvFavAdapter = new FavoriteAdapter(getContext(), dictionaryDB,wordList);
rv.setAdapter(rvFavAdapter);
else
Toast.makeText(getContext(), "You have no bookmark yet.", Toast.LENGTH_SHORT).show();
return view;
When i use bookmark codes from direct RecyclerView
When i use same bookmark codes from another fragment this happens
任何帮助将不胜感激 ????
【问题讨论】:
【参考方案1】:问题解决
只需将它们添加到 RecyclerView
int position = this.getAdapterPosition();
Word word = wordList.get(position);
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
并将此代码添加到片段类
word = new Word(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null)
word = bundle.getParcelable("allData");
termTextView.setText(word.getSanskrit());
descTextView.setText(word.getBangla());
*** 你需要让你的 POJO 类 Parcelable 在片段之间传递对象。 ***
【讨论】:
以上是关于如果我想从另一个片段中添加书签,为啥我的书签单词没有保存到 sqlite 数据库?的主要内容,如果未能解决你的问题,请参考以下文章