Home > Net >  Why my bookmarked words doesn't saved to sqlite database if i want to add them from another fra
Why my bookmarked words doesn't saved to sqlite database if i want to add them from another fra

Time:11-15

The main problem is that when i add bookmark codes from direct recyclerview it works perfectly fine but when i add those codes to another fragment it just only show a toast that bookmark is added or deleted but that bookmarked word doesn't show in favorite list.

Here is my Database codes


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();
    }
    
}



My RecyclerView codes



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);

             
             
         }
         
    
}
    


}

My Detalis Fragment codes


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();
        }
               
           
    }}

My Favorite Fragment codes


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

Any help will be heavily appreciated

  • Related