Instantly not able to delete contents from Calendar

58 Views Asked by At

`I'm facing an issue with the ListView in an Android app where I'm able to delete an event from the listview using a content resolver. The deletion is reflected instantly in the ListView, but when I reopen the ListView, the deleted items start appearing again. The items are only deleted permanently after a few minutes of delay.What could be the issue??

Below is my listview displaying and deletion code as well content resolver code for event reading and deleting

Calendar_ListView.java

package com.example.eventhub;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import java.util.ArrayList;

public class Calendar_ListView extends AppCompatActivity {
    public ArrayList<String> Events_Name = new ArrayList<String>();
    public ArrayList<String> temporary = new ArrayList<String>();
    ArrayAdapter arrayAdapter;

    Utility utility;

    Context context;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reminder_list_view);

        context = getApplicationContext();
        utility = new Utility(context);

        RelativeLayout relativeLayout = findViewById(R.id.ListId);
        AnimationDrawable animationDrawable = (AnimationDrawable) relativeLayout.getBackground();
        animationDrawable.setEnterFadeDuration(3500);
        animationDrawable.setExitFadeDuration(5500);
        animationDrawable.start();
        ListView listview = findViewById(R.id.listview);
//        Fetch_EventNames();

//        Log.d("FETCH_ON_CREATE", Events_Name.toString());
//        Log.d("FETCH_ON_CREATE", temporary.toString(  ));
//        Log.d("LISTVIEW", Events_Name.toString());

        arrayAdapter = new ArrayAdapter(Calendar_ListView.this, R.layout.listview_custom_itemview, temporary);

        listview.setAdapter(arrayAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Calendar_ListView.this);
                builder.setMessage("Do you want to delete this reminder?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // Perform delete action here
//                                Utility utility = new Utility();
                                utility.deleteEventByTitle2(context, Events_Name.get(position));
                                Log.d("FETCH", Events_Name.toString());
                                Log.d("FETCH", temporary.toString());
                                arrayAdapter.remove(arrayAdapter.getItem(position));
//                                Events_Name.remove(position);
//                                temporary.remove(position);
//                                arrayAdapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User cancelled the dialog
                                dialog.dismiss();
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });

    }
    @Override
    protected void onResume() {
        super.onResume();
        Fetch_EventNames();
        Log.d("LISTVIEW", Events_Name.toString());
        arrayAdapter.notifyDataSetChanged();
    }
    public void Fetch_EventNames(){
//        Utility utility = new Utility();
        utility.readCalendarEvent(context);
        Events_Name.clear();
        temporary.clear();
        ArrayList<String> titles = utility.nameOfEvent;
        ArrayList<String> myEvents = new ArrayList<String>();
        for(String str : titles){
            if(str != null && str.length() > 3 && str.substring(str.length() - 3).equals("_eh")){
                myEvents.add(str);
            }
        }
        Events_Name = myEvents;
        for(String str : Events_Name){
            temporary.add(str.substring(0, str.length()-3));
        }
//        Log.d("REMINDER_MY_EVENTS", myEvents.toString());
    }
}

Utility.java

package com.example.eventhub;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract;
import android.util.Log;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class Utility {
    public ArrayList<String> nameOfEvent = new ArrayList<String>();
    public ArrayList<ArrayList<String>> Event_Start_End = new ArrayList<ArrayList<String>>();

    public ArrayList<String> startDates = new ArrayList<String>();
    public ArrayList<String> endDates = new ArrayList<String>();
    public ArrayList<String> descriptions = new ArrayList<String>();
    public ArrayList<String> eventIds = new ArrayList<String>();
    ContentResolver resolver;
    public Utility(Context context){
        resolver = context.getContentResolver();
    }

    public ArrayList<String> readCalendarEvent(Context context) {

//        Cursor cursor = context.getContentResolver()
        Cursor cursor = resolver
                .query(
                        Uri.parse("content://com.android.calendar/events"),
                        new String[]{"calendar_id", "title", "description",
                                "dtstart", "dtend", "eventLocation"}, null,
                        null, null);
        cursor.moveToFirst();
        // fetching calendars name
        String CNames[] = new String[cursor.getCount()];

        // fetching calendars id
        nameOfEvent.clear();
        startDates.clear();
        endDates.clear();
        descriptions.clear();
        Log.d("UTILITY_OBJ", "SIZE: "+ Integer.toString(cursor.getCount()));

        for (int i = 0; i < CNames.length; i++) {
            String str1="", str2, str3;
//            ArrayList<String> temp = new ArrayList<String>(3);
            nameOfEvent.add(cursor.getString(1));

            if(cursor.getString(3) != null){
                startDates.add(getDate(Long.parseLong(cursor.getString(3))));

            }
            if(cursor.getString(4) != null){
                endDates.add(getDate(Long.parseLong(cursor.getString(4))));
            }
            descriptions.add(cursor.getString(2));
            CNames[i] = cursor.getString(1);
            cursor.moveToNext();
        }
        return nameOfEvent;
    }
    public void deleteEventByTitle(Context context, String title) {
//        ContentResolver cr = context.getContentResolver();

        Cursor cursor = resolver.query(
                Uri.parse("content://com.android.calendar/events"),
                new String[]{"_id"},
                "title=?",
                new String[]{title},
                null);

        if (cursor.moveToFirst()) {
            int temp = cursor.getColumnIndex("_id");
            long id;
            if(temp >= 0) {
                id = cursor.getLong(temp);
                Uri deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
//                int rows = cr.delete(deleteUri, null, null);
                int rows = resolver.delete(deleteUri, null, null);

                Log.d("UTILITY_OBJ", "Rows deleted: " + rows);
                Toast.makeText(context, "Event Successfully Deleted", Toast.LENGTH_SHORT).show();

            }
            else {
                Log.d("UTILITY_OBJ", "EVENT ID NOT FOUND");
                Toast.makeText(context, "Event NOT FOUND!!", Toast.LENGTH_SHORT).show();
            }
        }
        else {
            Log.d("UTILITY_OBJ", "EVENT ID NOT FOUND");
            Toast.makeText(context, "Event NOT FOUND!!", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }

    public String getDate(long milliSeconds) {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "dd/MM/yyyy hh:mm:ss a");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds);
        return formatter.format(calendar.getTime());
    }
    public ArrayList<String> readCalendarEvent2(Context context) {
        Cursor cursor = context.getContentResolver().query(
                Uri.parse("content://com.android.calendar/events"),
                new String[]{"_id", "calendar_id", "title", "description",
                        "dtstart", "dtend", "eventLocation"}, null, null, null);
        cursor.moveToFirst();
        // fetching calendars name
        String CNames[] = new String[cursor.getCount()];

        // fetching calendars id
        nameOfEvent.clear();
        startDates.clear();
        endDates.clear();
        descriptions.clear();
        eventIds.clear(); // List to store event IDs
        Log.d("UTILITY_OBJ", "SIZE: "+ Integer.toString(cursor.getCount()));

        for (int i = 0; i < CNames.length; i++) {
            eventIds.add(cursor.getString(0)); // Add event ID to list
            nameOfEvent.add(cursor.getString(2));
            if(cursor.getString(4) != null){
                startDates.add(getDate(Long.parseLong(cursor.getString(4))));
            }
            if(cursor.getString(5) != null){
                endDates.add(getDate(Long.parseLong(cursor.getString(5))));
            }
            descriptions.add(cursor.getString(3));
            CNames[i] = cursor.getString(2);
            cursor.moveToNext();
        }
        return nameOfEvent;
    }

    public void deleteEventByTitle2(Context context, String title) {
        Cursor cursor = resolver.query(
                Uri.parse("content://com.android.calendar/events"),
                new String[]{"_id"},
                "title=?",
                new String[]{title},
                null);

        ArrayList<String> eventsToDelete = new ArrayList<String>();

        if (cursor.moveToFirst()) {
            int temp = cursor.getColumnIndex("_id");
            long id;
            if(temp >= 0) {
                id = cursor.getLong(temp);
                eventsToDelete.add(title);
                Uri deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
                int rows = resolver.delete(deleteUri, null, null);

                Log.d("UTILITY_OBJ", "Rows deleted: " + rows);
                Toast.makeText(context, "Event Successfully Deleted", Toast.LENGTH_SHORT).show();

            }
            else {
                Log.d("UTILITY_OBJ", "EVENT ID NOT FOUND");
                Toast.makeText(context, "Event NOT FOUND!!", Toast.LENGTH_SHORT).show();
            }
        }
        else {
            Log.d("UTILITY_OBJ", "EVENT ID NOT FOUND");
            Toast.makeText(context, "Event NOT FOUND!!", Toast.LENGTH_SHORT).show();
        }
        cursor.close();

        // remove eventsToDelete from nameOfEvent ArrayList
        for (String event : eventsToDelete) {
            nameOfEvent.remove(event);
        }
    }


}

I tried making a single instance of content resolver but still didn't do any good.`

0

There are 0 best solutions below