0

I have a problem with the duplicate items in my list. I want to view my items from my database. If you want, in top of the list, there is the last item from database and if you scroll down you will see the historic (the rest element of database) but I don't know why... I have duplicate items here. Anyone can help me?

Code:

/**
 * A fragment representing a list of Items.
 * <p/>
 * Large screen devices (such as tablets) are supported by replacing the ListView
 * with a GridView.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
 * interface.
 */
public class PlacesFragment extends Fragment implements AbsListView.OnItemClickListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public static final int PAGE_SIZE = 5;
    public static final int LIST_INIT_SIZE = 1;
    ImageView imageView;
    String[] test;
    String text = "Central Park";
    Date data = new Date();
    String data_database = String.valueOf(data);
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private OnFragmentInteractionListener mListener;
    final List<PlaceListItem> items = new ArrayList<>();
    /**
     * The fragment's ListView/GridView.
     */
    private AbsListView mListView;
    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private ListAdapter mAdapter;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public PlacesFragment() {
    }

    // TODO: Rename and change types of parameters
    public static PlacesFragment newInstance(String param1, String param2) {
        PlacesFragment fragment = new PlacesFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // TODO: Change Adapter to display your content
//        mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_place, container, false);
        Context ctx = view.getContext();

        final DataBase dataBase = new DataBase(getActivity().getApplicationContext());
        SQLiteDatabase db = dataBase.getReadableDatabase();
        Cursor cr = dataBase.getInformation(dataBase);
        cr.moveToFirst();

//        if (!db.isOpen()) {
//            dataBase.onCreate(db);
//        }
//        dataBase.onCreate(db);
        //ctx.deleteDatabase(DataBase.TABLE_NAME);
        final DetectionLocation detectionLocation = new DetectionLocation(ctx);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        Integer val = Integer.valueOf(prefs.getString("sync_frequency", ""));
        final String sync_status = String.valueOf(val);


        dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);

        mListView = (AbsListView) view.findViewById(android.R.id.list);


        for (int i = 0; i < LIST_INIT_SIZE; i++) {
            items.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));
            cr.moveToNext();
        }

        final CustomListAdapter adapter = new CustomListAdapter(getActivity(), items);

//        dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);

        EndlessScrollListener scroll = new EndlessScrollListener(PAGE_SIZE) {
            Cursor cr = dataBase.getInformation(dataBase);

            @Override
            public void onLoadMore(int page, int totalItemsCount) {
                cr.moveToFirst();


//                dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);

                for (int i = 0; i < totalItemsCount; i++) {
                    if (cr.isLast()) {
                        break;
                    }
                    items.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));
//                    adapter.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));
                    adapter.add(items.get(i));
                    cr.moveToNext();
                }
                adapter.notifyDataSetChanged();
            }
        };

//        mListView.setOnScrollListener(scroll);
//        mListView.setAdapter(adapter);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Cursor cr = dataBase.getInformation(dataBase);
                        cr.moveToFirst();
                        if (!data.toString().equals(cr.getString(4))) {
                            dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "N", data, sync_status);
                        }
//                         TODO get newest entries and append on list
                        //items.add(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)));

                        adapter.insert(new PlaceListItem(cr.getString(4), cr.getString(1), cr.getString(2)), 0);//
                        adapter.notifyDataSetChanged();
                        // mListView.invalidateViews();
                    }
                });
            }
        }, 2/*val*/);
        mListView.setOnScrollListener(scroll);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
            mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
        }
    }

    /**
     * The default content for this Fragment has a TextView that is shown when
     * the list is empty. If you would like to change the text, call this method
     * to supply the text it should use.
     */

    public void setEmptyText(CharSequence emptyText) {
        View emptyView = mListView.getEmptyView();

        if (emptyView instanceof TextView) {
            ((TextView) emptyView).setText(emptyText);
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(String id);
    }

}

You can see on the following image that there are duplicate items (looking just on date). Link : https://i.stack.imgur.com/thN1Z.png

romfret
  • 391
  • 2
  • 11
cavaler12345
  • 367
  • 1
  • 5
  • 15
  • 7
    Can you use a `Set` instead? Sets automatically handle duplicates. – Dragondraikk May 21 '15 at 15:03
  • 2
    Just to add to @Dragondraikk comment if you have a set of object you created you will need to create a hashCode and equals method for that object to see the correct behavior. – StackFlowed May 21 '15 at 15:08
  • PlaceListItem is an object, and not a simple String type. Therefore you have to define a way to compare strings in that object. Post code for PlaceListItem, at least for the data structure. I have used Interface Comparable defined in my class. I may post answer later when I have time. – The Original Android May 21 '15 at 19:32

1 Answers1

0

I have solved this issue passing the data in a set, that automatically remove duplicates.

LinkedHashSet<String> hs = new LinkedHashSet();
hs.addAll(items);
items.clear();
items.addAll(hs);
Giacomo De Bacco
  • 723
  • 6
  • 26