0

i have a simple use case here, a list of words saved using shardpreferences, displayed using recycler view. i need to add words and delete words

to add words:

public void get_word(String new_word) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(String.valueOf(sharedPreferences.getAll().size()), new_word);
        System.out.println(sharedPreferences.getAll());
        editor.commit();
        vocabL.add(new_word);
        adapter.notifyItemInserted(vocabL.size() - 1);
        VVlist.scrollToPosition(vocabL.size() -1);
    }

the idea here is quite simple and buggy, the keys im using for shared preferences are numbers, so here i used the size function which would return the next number i can use but here is the issue:

 public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
        holder.textView.setText(list.get(position));
        holder.textView.setOnClickListener(v -> Toast.makeText(context, "Clicked on " + holder.getAbsoluteAdapterPosition(), Toast.LENGTH_SHORT).show());
        holder.textView.setOnLongClickListener(view -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle("Delete word")
                    .setMessage("are you sure you want to delete?")
                    .setPositiveButton("yes", (dialogInterface, i) -> {
                        list.remove(holder.getAbsoluteAdapterPosition());                        editor.remove(String.valueOf(holder.getAbsoluteAdapterPosition()));
                        notifyItemRemoved(holder.getAbsoluteAdapterPosition());
                        editor.commit();
                    })
                    .setNegativeButton("no", (dialogInterface, i) -> {

                    });
            builder.show();
            return true;
        });
    }

here when i delete a word, i loose the key as well so i guess the problem is clear, the next time i try to add a word, i override an existing value also there are other problems with this inefficient code, when deleting, the position can differ to the key, hence deleting something that wasnt meant to be deleted

there is a list 'list' in the above code, which is nothing but a list containing all the words, i used it for testing possible solutions

im self taught, im not aware of the right programming practises to use here. the only possible solution i can think of is using the map interface, but i feel like there are better ways to go around this thanks

SCS
  • 23
  • 6

2 Answers2

1

This is how I'd do it.

1.Have a model for the words

data class Word(var id:Long,var word:String)

2.Populate a list of the words for the recycler view. For ID, use System.nanotime() & 0xfffff. This guarantees a unique ID every time it is called( at least I tested it against a million iterations).

val wordlist= mutableListOf<Word>()

for (s in 0 until 10){
val word=Word((System. nanotime & 0xfffff).toLong(),"Some random string")

worldList.add(word)
//save the word to preference with the key word.id

  1. In your adapter in onBindViewHolder
val word= worldList[position]

yourTextView.text=word

yourDeleteView.setOnClickListener{
val wordID=word.id
deleteWord(wordID)
}
return 0
  • 132
  • 5
  • small problem, when i do the "getadapterposition" it returns an int of its location, now this is the only method i can use to know which item was selected, or this is the only method im aware of. like i said earlier i'd have to map the positions to the keys. – SCS Feb 28 '22 at 19:48
  • You don't have to with my approach because is word is an object with its own ID and the word itself. – return 0 Feb 28 '22 at 19:56
  • The overridden onBindViewHolder has a position parameter. – return 0 Feb 28 '22 at 19:58
  • hmm, if u dont mind, can you provide the code using java? – SCS Feb 28 '22 at 20:01
  • yes, the position parameter iterates the size provided, there is another function which i had to override and return the size of the list – SCS Feb 28 '22 at 20:02
  • or thts what i think what happens – SCS Feb 28 '22 at 20:03
  • Let me do the whole thing in Java and send you a github link – return 0 Feb 28 '22 at 20:26
  • i went through ur answer again, let me know if i got this right: i should set an id for the string, and use the same id as the key in shared pref then at the view holder? how do ik which word was selected? – SCS Feb 28 '22 at 20:32
  • You get it's ID. The word class has two fields – return 0 Feb 28 '22 at 20:43
  • Aight I did some digging, there is a method getitemid(), is that what you were referring to? So this function returns the ID of the string yes? – SCS Feb 28 '22 at 20:45
0
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.textView.setText(pist.get(position).toString());
        holder.textView.setTag(pist.get(position).toString());
        holder.textView.setOnClickListener(v -> Toast.makeText(context, "Clicked on " + holder.getAbsoluteAdapterPosition(), Toast.LENGTH_SHORT).show());
        holder.textView.setOnLongClickListener(view -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle("Delete word")
                    .setMessage("are you sure you want to delete?")
                    .setPositiveButton("yes", (dialogInterface, i) -> {
                        pist.remove(holder.getAbsoluteAdapterPosition());
                        editor.remove(String.valueOf(view.getTag()));
                        notifyItemRemoved(holder.getAbsoluteAdapterPosition());
                        editor.commit();
                    })
                    .setNegativeButton("no", (dialogInterface, i) -> {

                    });
            builder.show();
            return true;
        });
    }

the solution i found is to use tags for identification, i made a list(pist) of all the values in the shared preferences and im using the words as the keys, since its more convenient, if needed we could always make another list of keys and set the tag accordingly im not sure if this is the professional way to go abt it, but it works fine and seems decent enough nevertheless Im still open to answers

SCS
  • 23
  • 6