-4

How can i prevent the dublicate data to be added in my ArrayList of class

When i will add a data to array list then it will check that whether it is dublicate or not if yes it will not add the data to ArrayList

I am using this code to prevent the adding of dublicate elements but it's not working 

Code

public class ScrollingActivity extends AppCompatActivity implements AdaptreForRecycler.OnItemClickListener {
private RecyclerView recyclerView;
private AdaptreForRecycler adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<ExampleItem> mExampleList;


private Gson gson;
private String json;
private Type type;

private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;


EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrolling);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    loadData();
    buildRecyclerView();

    editText = findViewById(R.id.editText);
    fabButoonClick();


}

public void saveData() {

    sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
    editor = sharedPreferences.edit();
    gson = new Gson();
    json = gson.toJson(mExampleList);

    editor.putString("text", json);
    editor.apply();

}

public void loadData() {

    sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
    gson = new Gson();
    json = sharedPreferences.getString("text", null);
    type = new TypeToken<ArrayList<ExampleItem>>() {
    }.getType();
    mExampleList = gson.fromJson(json, type);

    if (mExampleList == null) {
        mExampleList = new ArrayList<>();
    }

}


public void insertItem(String text) {

    ExampleItem ex = new ExampleItem(text);


    if ( mExampleList.contains(ex)) {
        Toast.makeText(this, "Already Exists", Toast.LENGTH_SHORT).show();
    } else {
        mExampleList.add(ex);
    }

    adapter.notifyDataSetChanged();


}

ExampleItem deletedIndex = null;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
    @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) {
        final int position = viewHolder.getAdapterPosition();
        String name = mExampleList.get(position).getText1();
        deletedIndex = (mExampleList.get(position));
        mExampleList.remove(position);

        sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.remove("text");

        saveData();

        editor.apply();
        adapter.notifyItemRemoved(position);

        Snackbar.make(recyclerView, name + " Deleted", Snackbar.LENGTH_LONG)
                .setAction("Undo", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mExampleList.add(position, deletedIndex);
                        adapter.notifyItemInserted(position);

                        saveData();

                    }
                }).show();
    }

    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

        new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)

                .addSwipeLeftBackgroundColor(ContextCompat.getColor(ScrollingActivity.this, R.color.my_background))
                .addSwipeLeftActionIcon(R.drawable.ic_delete_black_24dp)
                .create()
                .decorate();
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }
};


private void buildRecyclerView() {
    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(ScrollingActivity.this);
    adapter = new AdaptreForRecycler(this, mExampleList);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);

}

public void fabButoonClick() {
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            AlertDialog.Builder b = new AlertDialog.Builder(ScrollingActivity.this);
            View mview = getLayoutInflater().inflate(R.layout.dialogbox_frontpage, null);

            final EditText editText = mview.findViewById(R.id.editText);
            b.setView(mview);
            b.setTitle("Add subject name");
            b.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String text = editText.getText().toString();

                    if (text.isEmpty()) {
                        Toast.makeText(ScrollingActivity.this, "Please add subject name", Toast.LENGTH_SHORT).show();
                    } else {

                        insertItem(text);

                        saveData();
                    }
                }
            });
            b.setCancelable(false);
            b.show();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_scrolling, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();


    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onItemClick(int position) {
    Intent i = new Intent(ScrollingActivity.this, StudentListActivity.class);
    i.putExtra("Subject Name", mExampleList.get(position).getText1());

    startActivity(i);
}

}

1

4 Answers 4

0

There's a pretty simple way to check if an item already exists in the list:

Override the equals method.

You will have to override the equals method inside your ExampleItem class.

I don't know the contents, ie. code, of your ExampleItem but this is just my guess so I suggest you to change your code accordingly.

public class ExampleItem {

    private String text1, text2;

    @Override
    public boolean equals(Object o) {
        // Check if the given Object 'o' is an instance,
        // ie. same class, of this ExampleItem class
        if (o instanceof ExampleItem) {
            // Cast the object to ExampleItem
            ExampleItem other = (ExampleItem) o;

            // Check if both have same text
            // (I'm guessing that you only wanted to
            //   compare the text1 variable, otherwise,
            //   check comment below.)
            // Objects.equals() will evaluate whether
            // both text are the same
            return Objects.equals(this.text1, other.text1); // 'this' is unnecessary, only to show

            // If you want to check both then uncomment
            // the code below and remove the one above
            // return Objects.equals(text1, other.text1) && Objects.equals(text2, other.text2);
        }

        // If above fails then I'll just use the
        // before-overwritten equals to avoid
        // writing myself each tiny bit of
        // its implementation
        return super.equals(o);
    }

    public ExampleItem(String text1) {
        this.text1 = text1;
    }

    public ExampleItem(String text1, String text2) {
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getText1() {
        return text1;
    }

    public void setText1(String t1) {
        text1 = t1;
    }

    public String getText2() {
        return text2;
    }

    public void setText2(String t2) {
        text2 = t2;
    }

}

The contains method of the List then will use your overridden/custom equals method to compare the given item to other items in it.

And that's it, just like a plug-and-play kinda code thing. You can now expect your mExampleList.contains(ex) to work.

And surely I hope that it does work and as always, happy coding!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank a lot it was so Pretty simple. I don't know why i got minus 4 votes for this question. I got the answer I'll mark it answerd
0

I am guessing you want to prevent duplicated elements to be added to ArrayList. But it is not ArrayList's strength. If you want to keep just unique elements, just use the HashSet data structure which will only retain unique elements. But what need extra attention is that how you define duplicates, whether two elements has same contents or they have same id(which is exactly the same object).

5 Comments

But i want that when I'll add the dublicate data it will show a toast message that data is already exits. Is it not possible
It is of course possible, HashSet has a contains(Object o) method which tell you if an element is already in the set, then this method gives you an true you can then invoke you toast message.
How can i use Hashset i didn't use it before
Use a mature side like eclipse and search for the class HashSet, it is in java.util package, and you will see elaborated comment on how it behaves so you can get an idea how to use it.
How can i get a single string data from a class eg. I have a HashSet<E> example = new HashSet<>() ; so i want to get data from class E how can i get that
0

This solution is a further extension adopted from this post.Unique value ArrayList It has all behaviors of array list since you can add and retrieve element as an ArrayList but keep uniqueness at the same time. Below is the code of the ArrayListSet that you can create on your own.

import java.util.*;

public class ArrayListSet<E> implements Iterable<E>, Set<E> {
    private ArrayList<E> list;
    private HashSet<E> set;

    public ArrayListSet() {
        list = new ArrayList<>();
        set = new HashSet<>();
    }

    public boolean add(E e) {
        return set.add(e) && list.add(e);
    }

    public boolean add(int i, E e) {
        if (!set.add(e)) return false;
        list.add(i, e);
        return true;
    }

    public void clear() {
        list.clear();
        set.clear();
    }

    public boolean contains(Object o) {
        return set.contains(o);
    }

    public E get(int i) {
        return list.get(i);
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }

    public E remove(int i) {        
        E e = list.remove(i);
        set.remove(e);
        return e;
    }

    public boolean remove(Object o) {        
        if (set.remove(o)) {
            list.remove(o);
            return true;
        }

        return false;
    }

    public boolean set(int i, E e) {
        if (set.contains(e)) return false;

        set.add(e);
        set.remove(list.set(i, e));
        return true;
    }

    public int size() {
        return list.size();
    }

    public void sort(Comparator<? super E> c) {
        Collections.sort(list, c);
    }

    public Iterator<E> iterator() {
        return list.iterator();
    }

    public boolean addAll(Collection<? extends E> c) {
        int before = size();
        for (E e : c) add(e);
        return size() == before;
    }

    public boolean containsAll(Collection<?> c) {
        return set.containsAll(c);
    }

    public boolean removeAll(Collection<?> c) {
        return set.removeAll(c) && list.removeAll(c);
    }

    public boolean retainAll(Collection<?> c) {
         return set.retainAll(c) && list.retainAll(c);
    }

    public Object[] toArray() {
        return list.toArray();
    }

    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }
}

Comments

0

Yes it is possible, you can use arrayList.contains(val) after scanning the val variable.

If it return 1, then print("val already exits.") otherwise,

If it returns 0, then you can add it in the arrayList

See how .contains() method work

You can also use .indexOf() method to find out the position. Refer here

To use .contains() with an Object You need to override hashcode and equals method . Refer here, watch the comments of marked Answer

4 Comments

as u said i tried it but its not solved my problem plz refer question i updated that
Where have you declared mExampleList ? Because this should work. Can you show me the complete code ? You can share a link of any git repo.
I declared the mExampleList globally and it is initialized when the mExampleList will null
Yeah got it, So the point is ArrayList.contains() method use .equals() method in its implemetation. So note that you need to change your equals method to accept an Object rather than a Thing. If you don't, your equals method won't be used. So just override your .equals() method to accept Object . Also override hashCode method too. Edited my answer (watch that link for more info on this point)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.