private RecyclerView recyclerView;
private FlashcardAdapter adapter;
private ArrayList<Flashcard> flashcardList;
private SharedPreferencesManager sharedPreferencesManager;
private FloatingActionButton fab;
private MaterialToolbar toolbar;
private Menu menu; // Mevcut menu referansı
private ActionMode actionMode; // Geçerli ActionMode
private ActionMode.Callback actionModeCallback;
// Yeni eklenecek: Etiket listesi
private ArrayList<String> tagList;
// Seçili etiket
private String selectedTag = "";
private String currentQuery = ""; // Yeni eklenen: Mevcut arama sorgusu
static Map<Integer, Integer> colorMap = new HashMap<>();
static Map<Integer, Integer> reverseColorMap = new HashMap<>();
// Benzersiz requestKey
private static final String REQUEST_KEY_UPDATE_TAGS_MAIN = "requestKey_updateTags_main";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Renk haritasını oluştur
// Renkleri colorMap'e ekle
colorMap.put(0xFF232531, 0xFFD3D6E3); // Koyu mavi -> Açık mavi
colorMap.put(0xFF482E5B, 0xFFE6D9ED); // Koyu mor -> Açık mor
colorMap.put(0xFF264D3B, 0xFFD9E6DD); // Koyu yeşil -> Açık yeşil
colorMap.put(0xFF274255, 0xFFD9E1E6); // Orta mavi -> Orta mavi
colorMap.put(0xFF256476, 0xFFD9E6E9); // Açık mavi -> Açık mavi
colorMap.put(0xFF232530, 0xFFD3D6E3); // Koyu gri -> Açık gri
colorMap.put(0xFF692A18, 0xFFE6D9D3); // Koyu kahverengi -> Açık kahverengi
colorMap.put(0xFF76172D, 0xFFE6D3D9); // Koyu kırmızı -> Açık kırmızı
colorMap.put(0xFF232428, 0xFFD3D6E3); // Koyu siyah -> Açık siyah
colorMap.put(0xFF4B443A, 0xFFE6E3D9); // Orta kahverengi -> Orta kahverengi
// Ters renk haritasını oluştur
for (Map.Entry<Integer, Integer> entry : colorMap.entrySet()) {
reverseColorMap.put(entry.getValue(), entry.getKey());
}
sharedPreferencesManager = new SharedPreferencesManager(this);
sharedPreferencesManager.applyNightMode();
recyclerView = findViewById(R.id.recyclerView);
fab = findViewById(R.id.fab);
flashcardList = new ArrayList<>();
tagList = new ArrayList<>(); // Etiket listesini başlat
adapter = new FlashcardAdapter(flashcardList, sharedPreferencesManager.isGoogleKeepModeEnabled(), this);
recyclerView.setAdapter(adapter);
// Layout manager'ı ayarla
applyRecyclerViewLayout();
toolbar = findViewById(R.id.materialToolbar);
setSupportActionBar(toolbar);
// Flashcard'ları okuma örneği
FirebaseManager.getInstance().getFlashcards(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
flashcardList.clear();
tagList.clear(); // Etiket listesini temizle
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Flashcard flashcard = dataSnapshot.getValue(Flashcard.class);
flashcardList.add(flashcard);
// Etiketleri topla, boş olmayanları
if (flashcard.getHashtags() != null) {
for (String tag : flashcard.getHashtags()) {
if (tag != null && !tag.trim().isEmpty()) {
tagList.add(tag.trim());
}
}
}
}
// Tekilleştirme
Set<String> uniqueTags = new HashSet<>(tagList);
tagList.clear();
tagList.addAll(uniqueTags);
Collections.sort(tagList); // İsteğe bağlı: Alfabetik sırala
// Sıralamayı uygula
sortLastUpdated();
adapter.filter(selectedTag, currentQuery); // Hem etiket hem arama ile filtreli listeleme
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "Failed to load data.", Toast.LENGTH_SHORT).show();
}
});
// FAB tıklama olayı
fab.setOnClickListener(view -> {
FragmentEdit addNoteFragment = new FragmentEdit();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, addNoteFragment);
transaction.addToBackStack(null);
transaction.commit();
//Circular Reveal animasyonu Güzel !
View fragmentContainer = findViewById(R.id.fragment_container);
int cx = (fragmentContainer.getLeft() + fragmentContainer.getRight()) / 2;
int cy = (fragmentContainer.getTop() + fragmentContainer.getBottom()) / 2;
int finalRadius = Math.max(fragmentContainer.getWidth(), fragmentContainer.getHeight());
Animator anim = ViewAnimationUtils.createCircularReveal(fragmentContainer, cx, cy, 0, finalRadius);
anim.setDuration(1000);
anim.setInterpolator(new DecelerateInterpolator());
fragmentContainer.setVisibility(View.VISIBLE);
anim.start();
fab.hide();
});
// RecyclerView tıklama dinleyicisini ayarla
adapter.setOnItemClickListener(new FlashcardAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (actionMode != null) {
toggleSelection(position);
} else {
// Filtrelenmiş flashcard listesinden seçilen flashcard'ı al
Flashcard selectedFlashcard = adapter.filteredFlashcards.get(position);
if (selectedFlashcard != null) {
// Fragment'a gönderilecek bilgileri Bundle ile paketle
Bundle bundle = new Bundle();
bundle.putString("id", selectedFlashcard.getId());
bundle.putString("category", selectedFlashcard.getCategory());
bundle.putString("title", selectedFlashcard.getTitle());
bundle.putString("content", selectedFlashcard.getContent());
bundle.putBoolean("favorite", selectedFlashcard.isFavorite());
bundle.putBoolean("pinned", selectedFlashcard.isPinned());
bundle.putString("backgroundColor", selectedFlashcard.getBackgroundColor());
bundle.putLong("timestamp", selectedFlashcard.getTimestamp());
bundle.putLong("updatedAt", selectedFlashcard.getUpdatedAt());
bundle.putLong("reminderTime", selectedFlashcard.getReminderTime());
bundle.putString("reminderFrequency", selectedFlashcard.getReminderFrequency());
// List<String> -> ArrayList<String> dönüşümü
List<String> hashtagsList = selectedFlashcard.getHashtags();
ArrayList<String> hashtagsArrayList = new ArrayList<>(hashtagsList);
bundle.putStringArrayList("hashtags", hashtagsArrayList);
// Fragment'ı oluştur ve Bundle'ı ileterek başlat
FragmentEdit editFragment = new FragmentEdit();
editFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, editFragment);
transaction.addToBackStack(null);
transaction.commit();
fab.hide();
}
}
}
@Override
public void onItemLongClick(View view, int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
});
// Geri tuşu için callback
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof OnBackPressedListener) {
((OnBackPressedListener) fragment).onBackPressed();
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
finish();
}
}
}
};
getOnBackPressedDispatcher().addCallback(this, callback);
actionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
boolean hasPinned = false;
boolean hasFavorite = false;
boolean allPinned = true;
boolean allFavorite = true;
// Seçili flashcardların durumlarını kontrol et
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.filteredFlashcards.get(position);
if (flashcard.isPinned()) {
hasPinned = true;
} else {
allPinned = false;
}
if (flashcard.isFavorite()) {
hasFavorite = true;
} else {
allFavorite = false;
}
}
// Pinned menü öğesini güncelle
MenuItem pinItem = menu.findItem(R.id.action_pin);
updateMenuItemIcon(pinItem, allPinned, hasPinned, R.drawable.ic_pin_filled, R.drawable.ic_pin_outlined);
// Favorite menü öğesini güncelle
MenuItem favItem = menu.findItem(R.id.action_fav);
updateMenuItemIcon(favItem, allFavorite, hasFavorite, R.drawable.ic_favorite_filled, R.drawable.ic_favorite_outlined);
return true; // Menü güncellemeleri için true döndürün
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_pin) {
boolean isPinned = !item.isChecked();
item.setChecked(isPinned);
item.setIcon(isPinned ? R.drawable.ic_pin_filled : R.drawable.ic_pin_outlined);
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.filteredFlashcards.get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), isPinned, flashcard.getHashtags(), flashcard.getBackgroundColor());
}
return true;
}
if (id == R.id.action_changenotecolor) {
showColorPaletteDialog();
}
if (id == R.id.action_fav) {
boolean isFavorite = !item.isChecked();
item.setChecked(isFavorite);
item.setIcon(isFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_outlined);
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.filteredFlashcards.get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), isFavorite, flashcard.isPinned(), flashcard.getHashtags(), flashcard.getBackgroundColor());
}
return true;
}
if (id == R.id.action_label) { // Etiket ekleme işlemini burada gerçekleştirin.
Set<Integer> selectedPositions = adapter.getSelectedItems();
Log.d("MainActivity", "Seçili öğe sayısı: " + selectedPositions.size());
if (selectedPositions.isEmpty()) {
Toast.makeText(MainActivity.this, "Hiçbir flashcard seçilmedi.", Toast.LENGTH_SHORT).show();
return true;
}
ArrayList<String> selectedFlashcardIds = new ArrayList<>();
ArrayList<String> existingCheckedTags = new ArrayList<>();
for (Integer position : selectedPositions) {
Flashcard flashcard = adapter.filteredFlashcards.get(position);
selectedFlashcardIds.add(flashcard.getId());
// İlk flashcard'ın etiketlerini alarak başlangıç etiketleri olarak kullan
if (existingCheckedTags.isEmpty()) {
existingCheckedTags.addAll(flashcard.getHashtags());
}
Log.d("MainActivity", "Seçili Flashcard ID: " + flashcard.getId());
}
// Fragmanı oluşturmak ve argümanları iletmek için newInstance metodunu kullan
LabelListFragment labelFragment = LabelListFragment.newInstance(tagList, selectedFlashcardIds, existingCheckedTags,REQUEST_KEY_UPDATE_TAGS_MAIN);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, labelFragment, "LabelListFragment");
transaction.addToBackStack(null);
transaction.commit();
fab.hide();
if (actionMode != null) {
actionMode.finish();
}
return true;
}
if (id == R.id.action_delete) {
deleteSelectedItems();
mode.finish();
return true;
}
// Diğer menü işlemleri (örneğin düzenleme) burada eklenebilir
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
adapter.clearSelections();
actionMode = null;
}
};
// Hamburger ikonuna tıklanma olayını dinlemek için
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTagSelectionDialog(); // Etiket seçim dialogunu göster
}
});
getSupportFragmentManager().setFragmentResultListener(REQUEST_KEY_UPDATE_TAGS_MAIN, this, new FragmentResultListener() {
@Override
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
//Toast.makeText(MainActivity.this, "onFragmentResult çağrıldı.", Toast.LENGTH_SHORT).show();
ArrayList<String> updatedTags = bundle.getStringArrayList("updatedTags");
ArrayList<String> selectedFlashcardIds = bundle.getStringArrayList("selectedFlashcardIds");
if (updatedTags != null && selectedFlashcardIds != null) {
// updatedTags listesinden boş dizeleri kaldır
updatedTags.removeAll(Collections.singleton(""));
//Toast.makeText(MainActivity.this, "updatedTags alındı: " + updatedTags.toString(), Toast.LENGTH_SHORT).show();
//Log.d("MainActivity", "Güncellenecek Flashcard Sayısı: " + selectedFlashcardIds.size());
for (String flashcardId : selectedFlashcardIds) {
Flashcard flashcard = getFlashcardById(flashcardId);
if (flashcard != null) {
List<String> finalHashtags;
if (updatedTags.isEmpty()) {
// updatedTags boş ise, hashtags listesine boş bir string ekleyin
finalHashtags = new ArrayList<>();
finalHashtags.add("");
} else {
// updatedTags boş değilse, şüpheli boş dizeleri kaldırıvermek için yeni bir liste oluştur
finalHashtags = new ArrayList<>(updatedTags);
}
// Flashcard'ın hashtags'ini güncelle
flashcard.setHashtags(finalHashtags);
// Firestore'da flashcard'ı güncelle
updateFlashcard(
flashcard.getId(),
flashcard.getCategory(),
flashcard.getTitle(),
flashcard.getContent(),
flashcard.isFavorite(),
flashcard.isPinned(),
finalHashtags,
flashcard.getBackgroundColor()
);
} else {
//Log.e("MainActivity", "Flashcard bulunamadı: " + flashcardId);
}
}
// Adapter'ı güncelle
adapter.notifyDataSetChanged();
} else {
//Log.e("MainActivity", "updatedTags veya selectedFlashcardIds eksik.");
//Toast.makeText(MainActivity.this, "Güncellenen etiketler veya flashcard ID'leri eksik.", Toast.LENGTH_SHORT).show();
}
}
});
// `FragmentEdit` içinden gelen `FragmentResultListener`
getSupportFragmentManager().setFragmentResultListener(
"requestKey_updateTags_edit",
this,
new FragmentResultListener() {
@Override
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
// Bu sonuç zaten `FragmentEdit` tarafından ele alınıyor
// Sonuçları burada ignore edebilirsiniz veya gerekirse farklı işlemler yapabilirsiniz
}
}
);
// Fragment değişikliklerini izlemek için OnBackStackChangedListener ekle
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
manageToolbarAndFabVisibility();
}
});
// İlk açılışta görünürlüğü kontrol et
manageToolbarAndFabVisibility();
}
/**
* Aktif olan fragmente bağlı olarak toolbar ve FAB'ın görünürlüğünü yönetir.
*/
private void manageToolbarAndFabVisibility(){
boolean hideToolbarAndFab = false;
// Tüm aktif fragmentları al
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for(Fragment fragment : fragments){
if(fragment instanceof FragmentEdit || fragment instanceof LabelListFragment){
hideToolbarAndFab = true;
break;
}
}
if(hideToolbarAndFab){
hideToolbar();
hideFab();
}
else{
showToolbar();
showFab();
}
}
/**
* Belirtilen ID'ye sahip flashcard'ı bulur.
*
* @param id Güncellenmesi gereken flashcard ID'si
* @return Bulunan Flashcard nesnesi veya null
*/
private Flashcard getFlashcardById(String id) {
for (Flashcard flashcard : adapter.filteredFlashcards) {
if (flashcard.getId().equals(id)) {
return flashcard;
}
}
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
this.menu = menu;
toolbar.setOverflowIcon(getDrawable(R.drawable.ic_menu_threedot));
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// Tamamlanma işlemi için false döndürün
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
currentQuery = newText; // Mevcut arama sorgusunu güncelle
adapter.filter(selectedTag, currentQuery); // Hem etikete hem aramaya göre filtrele
return true;
}
});
// Menü öğesinin ikonunu başlangıç durumuna göre ayarla
updateMenuIcon(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
if (id == R.id.action_night_mode) {
toggleNightMode();
return true;
}
if (id == R.id.action_googlekeepmode) {
sharedPreferencesManager.toggleGoogleKeepMode();
recreate();
return true;
}
if (id == R.id.action_sort) {
ShowPopUpSortMenu(findViewById(R.id.action_sort));
return true;
}
if (id == R.id.action_change_recycleview_layout) {
// Mevcut görünüm türünü al
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
// Yeni görünüm türünü belirle
SharedPreferencesManager.ViewType newViewType;
switch (currentViewType) {
case LIST:
newViewType = SharedPreferencesManager.ViewType.GRID;
break;
case GRID:
newViewType = SharedPreferencesManager.ViewType.STAGGERED_GRID;
break;
case STAGGERED_GRID:
default:
newViewType = SharedPreferencesManager.ViewType.LIST;
break;
}
// Yeni görünüm türünü ayarla
sharedPreferencesManager.setRecyclerViewLayout(newViewType);
// Menüdeki ikonları güncelle
updateMenuIcon(menu); // Değiştirilen ikonları güncelle
// RecyclerView layout'unu uygula
applyRecyclerViewLayout();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Seçili öğeleri siler ve Firebase'den kaldırır.
*/
private void deleteSelectedItems(){
Set<Integer> selectedPositions = adapter.getSelectedItems();
ArrayList<Flashcard> itemsToDelete = new ArrayList<>();
// Seçilen öğeleri toplamak
for(Integer pos : selectedPositions){
itemsToDelete.add(adapter.filteredFlashcards.get(pos));
}
// Hem yerel listeden hem de Firebase'den silme işlemi
for(Flashcard flashcard : itemsToDelete){
// Firebase'den sil
FirebaseManager.getInstance().deleteFlashcard(flashcard.getId());
// Yerel listeden sil
flashcardList.remove(flashcard);
}
// Etiket listesini güncelle
updateTagList();
// Adapter'den filtreli listeyi güncelle
adapter.filter(selectedTag, currentQuery);
Toast.makeText(this, itemsToDelete.size() + " flashcard(s) deleted.", Toast.LENGTH_SHORT).show();
}
/**
* Çoğul seçim durumunu yönetir.
* @param position Seçili öğenin konumu
*/
private void toggleSelection(int position){
adapter.toggleSelection(position);
int count = adapter.getSelectedItemCount();
if(count == 0){
if(actionMode != null){
actionMode.finish();
}
} else {
actionMode.setTitle(count + " selected");
actionMode.invalidate();
}
}
private void toggleNightMode() {
sharedPreferencesManager.toggleNightMode();
onNightModeChanged(!sharedPreferencesManager.isNightModeEnabled());
recreate();
}
private void updateMenuIcon(Menu menu) {
// Menü öğesinin ikonunu görünüm türüne göre ayarla
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
MenuItem item = menu.findItem(R.id.action_change_recycleview_layout);
switch (currentViewType) {
case LIST:
item.setIcon(R.drawable.ic_vertical_list_icon);
break;
case GRID:
item.setIcon(R.drawable.ic_gridview_icon);
break;
case STAGGERED_GRID:
item.setIcon(R.drawable.ic_staggeredgridview_icon); // Staggered grid için ikon ekle
break;
}
}
private void applyRecyclerViewLayout() {
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
switch (currentViewType) {
case LIST:
recyclerView.setLayoutManager(new LinearLayoutManager(this));
break;
case GRID:
recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); // 2 sütunlu grid
break;
case STAGGERED_GRID:
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); // 2 sütunlu staggered grid
break;
}
adapter.notifyDataSetChanged(); // Adapter'ı bilgilendir
}
public interface OnBackPressedListener {
void onBackPressed();
}
// Toolbar'ı gizlemek için yardımcı metod
public void hideToolbar() {
if (toolbar != null) {
toolbar.setVisibility(View.GONE);
}
}
// Toolbar'ı göstermek için yardımcı metod
public void showToolbar() {
if (toolbar != null) {
toolbar.setVisibility(View.VISIBLE);
}
}
// FAB'ı gizlemek için yardımcı metod
public void hideFab() {
if (fab != null) {
fab.hide();
}
}
// FAB'ı göstermek için yardımcı metod
public void showFab() {
if (fab != null) {
fab.show();
}
}
// ... Önceki kodlarınızın devamı ...
public void ShowPopUpSortMenu(View anchorView) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, anchorView);
popupMenu.getMenuInflater().inflate(R.menu.sort_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.sort_alphabetically) {
sortAlphabetically();
return true;
} else if (itemId == R.id.sort_newest) {
sortNewest();
return true;
} else if (itemId == R.id.sort_oldest) {
sortOldest();
return true;
} else if (itemId == R.id.sort_last_updated) {
sortLastUpdated();
return true;
}
return false;
}
});
popupMenu.show();
}
/**
* Flashcard listesini pinned durumuna ve zamanına göre sıralar.
*/
/**
* Ortak sıralama fonksiyonu. pinned olanlar her zaman üstte kalır ve kendilerine özel sıralama uygulanır.
* @param comparator Sıralama için kullanılacak Comparator.
*/
private void sortFlashcards(Comparator<Flashcard> comparator) {
Collections.sort(flashcardList, new Comparator<Flashcard>() {
@Override
public int compare(Flashcard o1, Flashcard o2) {
// Pinned kontrolü
if (o1.isPinned() && !o2.isPinned()) {
return -1; // o1 önce gelir
} else if (!o1.isPinned() && o2.isPinned()) {
return 1; // o2 önce gelir
} else if (o1.isPinned() && o2.isPinned()) {
// Her iki öğe de pinned ise, updatedAt'a göre sırala (azalan)
return Long.compare(o2.getUpdatedAt(), o1.getUpdatedAt());
} else {
// Her iki öğe de pinned değil ise, verilen comparator ile sırala
return comparator.compare(o1, o2);
}
}
});
}
/**
* Flashcard listesini alfabetik olarak sıralar ve pinned olanlar her zaman üstte kalır.
*/
private void sortAlphabetically() {
Comparator<Flashcard> alphabeticalComparator = new Comparator<Flashcard>() {
@Override
public int compare(Flashcard o1, Flashcard o2) {
return o1.getTitle().compareToIgnoreCase(o2.getTitle());
}
};
sortFlashcards(alphabeticalComparator);
adapter.filter(selectedTag, currentQuery); // Hem etikete hem aramaya göre filtrele
Toast.makeText(this, "Alfabetik olarak sıralandı.", Toast.LENGTH_SHORT).show();
}
/**
* Flashcard listesini en yeniye göre sıralar ve pinned olanlar her zaman üstte kalır.
*/
private void sortNewest() {
Comparator<Flashcard> newestComparator = new Comparator<Flashcard>() {
@Override
public int compare(Flashcard o1, Flashcard o2) {
return Long.compare(o2.getTimestamp(), o1.getTimestamp()); // Büyükten küçüğe
}
};
sortFlashcards(newestComparator);
adapter.filter(selectedTag, currentQuery); // Hem etikete hem aramaya göre filtrele
Toast.makeText(this, "En yeniye göre sıralandı.", Toast.LENGTH_SHORT).show();
}
/**
* Flashcard listesini en eskiye göre sıralar ve pinned olanlar her zaman üstte kalır.
*/
private void sortOldest() {
Comparator<Flashcard> oldestComparator = new Comparator<Flashcard>() {
@Override
public int compare(Flashcard o1, Flashcard o2) {
return Long.compare(o1.getTimestamp(), o2.getTimestamp()); // Küçükten büyüğe
}
};
sortFlashcards(oldestComparator);
adapter.filter(selectedTag, currentQuery); // Hem etikete hem aramaya göre filtrele
Toast.makeText(this, "En eskiye göre sıralandı.", Toast.LENGTH_SHORT).show();
}
/**
* Flashcard listesini en son güncellenene göre sıralar ve pinned olanlar her zaman üstte kalır.
*/
private void sortLastUpdated() {
Comparator<Flashcard> lastUpdatedComparator = new Comparator<Flashcard>() {
@Override
public int compare(Flashcard o1, Flashcard o2) {
return Long.compare(o2.getUpdatedAt(), o1.getUpdatedAt()); // Büyükten küçüğe
}
};
sortFlashcards(lastUpdatedComparator);
adapter.filter(selectedTag, currentQuery); // Hem etikete hem aramaya göre filtrele
//Toast.makeText(this, "En son güncellenene göre sıralandı.", Toast.LENGTH_SHORT).show();
}
/**
* Etiket seçim dialogunu gösterir.
*/
private void showTagSelectionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Etiket Seçin");
// "Tüm Etiketler" seçeneği ekle
ArrayList<String> displayTags = new ArrayList<>();
displayTags.add("Tüm Etiketler");
displayTags.addAll(tagList);
String[] tagsArray = displayTags.toArray(new String[0]);
builder.setItems(tagsArray, (dialog, which) -> {
if (which == 0) {
// "Tüm Etiketler" seçildi
selectedTag = "";
adapter.filter(selectedTag, currentQuery); // Mevcut arama sorgusunu dikkate al
Toast.makeText(MainActivity.this, "Tüm Etiketler seçildi.", Toast.LENGTH_SHORT).show();
} else {
// Belirli bir etiket seçildi
selectedTag = tagsArray[which];
adapter.filter(selectedTag, currentQuery); // Mevcut arama sorgusunu dikkate al
Toast.makeText(MainActivity.this, selectedTag + " etiketi seçildi.", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("İptal", (dialog, which) -> {
dialog.dismiss();
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Flashcard listesini, liste içindeki etiketleri güncelleyerek tekilleştirir.
*/
private void updateTagList() {
tagList.clear();
for (Flashcard flashcard : flashcardList) {
if (flashcard.getHashtags() != null) {
for (String tag : flashcard.getHashtags()) {
if (tag != null && !tag.trim().isEmpty()) {
tagList.add(tag.trim());
}
}
}
}
// Tekilleştirme
Set<String> uniqueTags = new HashSet<>(tagList);
tagList.clear();
tagList.addAll(uniqueTags);
Collections.sort(tagList); // İsteğe bağlı: Alfabetik sırala
}
/**
* Flashcard verisini günceller.
*
* @param id Flashcard ID'si.
* @param category Kategori adı.
* @param title Başlık.
* @param content İçerik.
* @param favorite Favori durumu.
* @param pinned Sabit durumu.
* @param hashtags Hashtag listesi.
*/
private void updateFlashcard(String id, String category, String title, String content, boolean favorite, boolean pinned, List<String> hashtags,String backgroundColor) {
Map<String, Object> updates = new HashMap<>();
updates.put("category", category);
updates.put("title", title);
updates.put("content", content);
updates.put("favorite", favorite);
updates.put("pinned", pinned);
updates.put("hashtags", hashtags); // Hashtag'ları ekliyoruz
updates.put("backgroundColor", backgroundColor);
long currentTimestamp = System.currentTimeMillis();
updates.put("updatedAt", currentTimestamp);
FirebaseManager.getInstance().updateFlashcard(id, updates);
}
// Menü öğelerini güncellemek için fonksiyon
private void updateMenuItemIcon(MenuItem item, boolean allSelected, boolean hasSelected, int filledIcon, int outlinedIcon) {
if (allSelected) {
item.setChecked(true);
item.setIcon(filledIcon);
} else if (hasSelected) {
item.setChecked(false); // Kısmi seçili durum, varsayılan olarak unchecked
item.setIcon(outlinedIcon);
} else {
item.setChecked(false);
item.setIcon(outlinedIcon);
}
}
public void showColorPaletteDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = LayoutInflater.from(this).inflate(R.layout.color_picker_dialog, null);
builder.setView(dialogView);
GridLayout colorGrid = dialogView.findViewById(R.id.colorGrid);
boolean isNightMode = sharedPreferencesManager.isNightModeEnabled();
final int[] colors;
if (isNightMode) {
// GoogleKeep DarkTema Not Renkleri
colors= new int[]{
R.drawable.ic_clear_color,
0xFF232531, // Koyu mavi
0xFF482E5B, // Koyu mor
0xFF264D3B, // Koyu yeşil
0xFF274255, // Orta mavi
0xFF256476, // Açık mavi
0xFF232530, // Koyu gri
0xFF692A18, // Koyu kahverengi
0xFF76172D, // Koyu kırmızı
0xFF232428, // Koyu siyah
0xFF4B443A // Orta kahverengi
};
} else {
// GoogleKeep DayTema Not Renkleri
colors = new int[]{
R.drawable.ic_clear_color,
0xFFD3D6E3, // Açık mavi
0xFFE6D9ED, // Açık mor
0xFFD9E6DD, // Açık yeşil
0xFFD9E1E6, // Orta mavi
0xFFD9E6E9, // Açık mavi
0xFFD3D6E3, // Açık gri
0xFFE6D9D3, // Açık kahverengi
0xFFE6D3D9, // Açık kırmızı
0xFFD3D6E3, // Açık siyah
0xFFE6E3D9 // Orta kahverengi
};
}
AlertDialog dialog = builder.create();
// İlk renk öğesi (renk kaldırma)
View firstColorItem = LayoutInflater.from(this).inflate(R.layout.color_item, null);
ImageView firstColorIconImgView = firstColorItem.findViewById(R.id.colorIcon);
firstColorIconImgView.setImageResource(colors[0]);
firstColorItem.setOnClickListener(v -> {
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.filteredFlashcards.get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), flashcard.isPinned(), flashcard.getHashtags(), "");
}
dialog.dismiss();
});
colorGrid.addView(firstColorItem, 0);
// Diğer renkler
for (int i = 1; i < colors.length; i++) {
final int color = colors[i];
View itemView = LayoutInflater.from(this).inflate(R.layout.color_item, null);
ImageView colorIcon = itemView.findViewById(R.id.colorIcon);
colorIcon.setBackgroundColor(color);
itemView.setOnClickListener(v -> {
String chosencolor = String.format("#%06X", (0xFFFFFF & color));
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.filteredFlashcards.get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), flashcard.isPinned(), flashcard.getHashtags(), chosencolor);
}
dialog.dismiss();
});
colorGrid.addView(itemView);
}
dialog.show();
}
// Gece modu değiştiğinde çağrılacak metod
public void onNightModeChanged(boolean isNightMode) {
List<Flashcard> flashcards = flashcardList;
for (Flashcard flashcard : flashcards) {
String backgroundColor = flashcard.getBackgroundColor();
if (backgroundColor != null && !backgroundColor.isEmpty()) {
int color = Color.parseColor(backgroundColor);
int tintColor;
if (isNightMode) {
tintColor = reverseColorMap.getOrDefault(color, color);
} else {
tintColor = colorMap.getOrDefault(color, color);
}
flashcard.setBackgroundColor(String.format("#%06X", (0xFFFFFF & tintColor)));
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), flashcard.isPinned(), flashcard.getHashtags(), flashcard.getBackgroundColor());
}
}
adapter.notifyDataSetChanged();
}
package com.example.newflashcard;
// ... [imports remain unchanged] ...
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private FlashcardAdapter adapter;
private ArrayList<Flashcard> flashcardList;
private SharedPreferencesManager sharedPreferencesManager;
private FloatingActionButton fab;
private MaterialToolbar toolbar;
private Menu menu; // Existing menu reference
private ActionMode actionMode; // Current ActionMode
private ActionMode.Callback actionModeCallback;
// New additions: Tag and Category lists
private ArrayList<String> tagList;
private Map<String, Integer> categoryCountMap;
private List<String> categoryList;
// Selected filters
private String selectedTag = "";
private String selectedCategory = "";
private String currentQuery = ""; // Current search query
static Map<Integer, Integer> colorMap = new HashMap<>();
static Map<Integer, Integer> reverseColorMap = new HashMap<>();
// Unique requestKey
private static final String REQUEST_KEY_UPDATE_TAGS_MAIN = "requestKey_updateTags_main";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize color maps as per existing code
// ... [existing color map initialization]
// Initialize SharedPreferencesManager and apply night mode
sharedPreferencesManager = new SharedPreferencesManager(this);
sharedPreferencesManager.applyNightMode();
recyclerView = findViewById(R.id.recyclerView);
fab = findViewById(R.id.fab);
flashcardList = new ArrayList<>();
tagList = new ArrayList<>();
categoryCountMap = new HashMap<>();
categoryList = new ArrayList<>();
adapter = new FlashcardAdapter(flashcardList, sharedPreferencesManager.isGoogleKeepModeEnabled(), this);
recyclerView.setAdapter(adapter);
// Set layout manager
applyRecyclerViewLayout();
toolbar = findViewById(R.id.materialToolbar);
setSupportActionBar(toolbar);
// Fetch flashcards from Firebase
FirebaseManager.getInstance().getFlashcards(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
flashcardList.clear();
tagList.clear();
categoryCountMap.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Flashcard flashcard = dataSnapshot.getValue(Flashcard.class);
if (flashcard != null) {
flashcardList.add(flashcard);
// Collect and count tags
if (flashcard.getHashtags() != null) {
for (String tag : flashcard.getHashtags()) {
if (tag != null && !tag.trim().isEmpty()) {
tagList.add(tag.trim());
}
}
}
// Collect and count categories
String category = flashcard.getCategory();
if (category != null && !category.trim().isEmpty()) {
category = category.trim();
categoryCountMap.put(category, categoryCountMap.getOrDefault(category, 0) + 1);
}
}
}
// Process unique tags
Set<String> uniqueTags = new HashSet<>(tagList);
tagList.clear();
tagList.addAll(uniqueTags);
Collections.sort(tagList); // Optional: Sort alphabetically
// Process unique categories
categoryList.clear();
categoryList.addAll(categoryCountMap.keySet());
Collections.sort(categoryList); // Optional: Sort alphabetically
// Apply sorting and filtering
sortLastUpdated();
adapter.filter(selectedTag, selectedCategory, currentQuery); // Updated to include category
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "Failed to load data.", Toast.LENGTH_SHORT).show();
}
});
// FAB click event
fab.setOnClickListener(view -> {
FragmentEdit addNoteFragment = new FragmentEdit();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, addNoteFragment);
transaction.addToBackStack(null);
transaction.commit();
// Circular Reveal animation
View fragmentContainer = findViewById(R.id.fragment_container);
int cx = (fragmentContainer.getLeft() + fragmentContainer.getRight()) / 2;
int cy = (fragmentContainer.getTop() + fragmentContainer.getBottom()) / 2;
int finalRadius = Math.max(fragmentContainer.getWidth(), fragmentContainer.getHeight());
Animator anim = ViewAnimationUtils.createCircularReveal(fragmentContainer, cx, cy, 0, finalRadius);
anim.setDuration(1000);
anim.setInterpolator(new DecelerateInterpolator());
fragmentContainer.setVisibility(View.VISIBLE);
anim.start();
fab.hide();
});
// RecyclerView click listener
adapter.setOnItemClickListener(new FlashcardAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (actionMode != null) {
toggleSelection(position);
} else {
// Get the selected flashcard from the filtered list
Flashcard selectedFlashcard = adapter.getFilteredFlashcards().get(position);
if (selectedFlashcard != null) {
// Prepare data to send to FragmentEdit
Bundle bundle = new Bundle();
bundle.putString("id", selectedFlashcard.getId());
bundle.putString("category", selectedFlashcard.getCategory());
bundle.putString("title", selectedFlashcard.getTitle());
bundle.putString("content", selectedFlashcard.getContent());
bundle.putBoolean("favorite", selectedFlashcard.isFavorite());
bundle.putBoolean("pinned", selectedFlashcard.isPinned());
bundle.putString("backgroundColor", selectedFlashcard.getBackgroundColor());
bundle.putLong("timestamp", selectedFlashcard.getTimestamp());
bundle.putLong("updatedAt", selectedFlashcard.getUpdatedAt());
bundle.putLong("reminderTime", selectedFlashcard.getReminderTime());
bundle.putString("reminderFrequency", selectedFlashcard.getReminderFrequency());
// Convert List<String> to ArrayList<String>
List<String> hashtagsList = selectedFlashcard.getHashtags();
ArrayList<String> hashtagsArrayList = new ArrayList<>(hashtagsList);
bundle.putStringArrayList("hashtags", hashtagsArrayList);
// Create and start FragmentEdit with the bundle
FragmentEdit editFragment = new FragmentEdit();
editFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, editFragment);
transaction.addToBackStack(null);
transaction.commit();
fab.hide();
}
}
}
@Override
public void onItemLongClick(View view, int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
});
// Handle back press
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof OnBackPressedListener) {
((OnBackPressedListener) fragment).onBackPressed();
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
finish();
}
}
}
};
getOnBackPressedDispatcher().addCallback(this, callback);
// ActionMode callback setup
actionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
boolean hasPinned = false;
boolean hasFavorite = false;
boolean allPinned = true;
boolean allFavorite = true;
// Check the state of selected flashcards
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.getFilteredFlashcards().get(position);
if (flashcard.isPinned()) {
hasPinned = true;
} else {
allPinned = false;
}
if (flashcard.isFavorite()) {
hasFavorite = true;
} else {
allFavorite = false;
}
}
// Update pin menu item
MenuItem pinItem = menu.findItem(R.id.action_pin);
updateMenuItemIcon(pinItem, allPinned, hasPinned, R.drawable.ic_pin_filled, R.drawable.ic_pin_outlined);
// Update favorite menu item
MenuItem favItem = menu.findItem(R.id.action_fav);
updateMenuItemIcon(favItem, allFavorite, hasFavorite, R.drawable.ic_favorite_filled, R.drawable.ic_favorite_outlined);
return true; // Return true to reflect changes
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_pin) {
boolean isPinned = !item.isChecked();
item.setChecked(isPinned);
item.setIcon(isPinned ? R.drawable.ic_pin_filled : R.drawable.ic_pin_outlined);
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.getFilteredFlashcards().get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), isPinned, flashcard.getHashtags(), flashcard.getBackgroundColor());
}
return true;
}
if (id == R.id.action_changenotecolor) {
showColorPaletteDialog();
return true;
}
if (id == R.id.action_fav) {
boolean isFavorite = !item.isChecked();
item.setChecked(isFavorite);
item.setIcon(isFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_outlined);
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.getFilteredFlashcards().get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), isFavorite, flashcard.isPinned(), flashcard.getHashtags(), flashcard.getBackgroundColor());
}
return true;
}
if (id == R.id.action_label) { // Handle label addition
Set<Integer> selectedPositions = adapter.getSelectedItems();
Log.d("MainActivity", "Number of selected items: " + selectedPositions.size());
if (selectedPositions.isEmpty()) {
Toast.makeText(MainActivity.this, "No flashcards selected.", Toast.LENGTH_SHORT).show();
return true;
}
ArrayList<String> selectedFlashcardIds = new ArrayList<>();
ArrayList<String> existingCheckedTags = new ArrayList<>();
for (Integer position : selectedPositions) {
Flashcard flashcard = adapter.getFilteredFlashcards().get(position);
selectedFlashcardIds.add(flashcard.getId());
// Use the tags of the first selected flashcard as initial checked tags
if (existingCheckedTags.isEmpty() && flashcard.getHashtags() != null) {
existingCheckedTags.addAll(flashcard.getHashtags());
}
Log.d("MainActivity", "Selected Flashcard ID: " + flashcard.getId());
}
// Create and show LabelListFragment
LabelListFragment labelFragment = LabelListFragment.newInstance(tagList, selectedFlashcardIds, existingCheckedTags, REQUEST_KEY_UPDATE_TAGS_MAIN);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, labelFragment, "LabelListFragment");
transaction.addToBackStack(null);
transaction.commit();
fab.hide();
if (actionMode != null) {
actionMode.finish();
}
return true;
}
if (id == R.id.action_delete) {
deleteSelectedItems();
mode.finish();
return true;
}
// Handle other menu actions if needed
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
adapter.clearSelections();
actionMode = null;
}
};
// Set navigation icon click to show category and tag selection dialog
toolbar.setNavigationOnClickListener(v -> showTagAndCategorySelectionDialog());
// FragmentResultListener for updating tags
getSupportFragmentManager().setFragmentResultListener(REQUEST_KEY_UPDATE_TAGS_MAIN, this, (requestKey, bundle) -> {
ArrayList<String> updatedTags = bundle.getStringArrayList("updatedTags");
ArrayList<String> selectedFlashcardIds = bundle.getStringArrayList("selectedFlashcardIds");
if (updatedTags != null && selectedFlashcardIds != null) {
// Remove empty strings
updatedTags.removeAll(Collections.singleton(""));
for (String flashcardId : selectedFlashcardIds) {
Flashcard flashcard = getFlashcardById(flashcardId);
if (flashcard != null) {
List<String> finalHashtags;
if (updatedTags.isEmpty()) {
finalHashtags = new ArrayList<>();
finalHashtags.add("");
} else {
finalHashtags = new ArrayList<>(updatedTags);
}
// Update flashcard's hashtags
flashcard.setHashtags(finalHashtags);
// Update in Firebase
updateFlashcard(
flashcard.getId(),
flashcard.getCategory(),
flashcard.getTitle(),
flashcard.getContent(),
flashcard.isFavorite(),
flashcard.isPinned(),
finalHashtags,
flashcard.getBackgroundColor()
);
}
}
// Update adapter
adapter.notifyDataSetChanged();
} else {
// Handle missing data if necessary
}
});
// Handle other incoming fragment results if needed
// Listen for fragment back stack changes to manage toolbar and FAB visibility
getSupportFragmentManager().addOnBackStackChangedListener(this::manageToolbarAndFabVisibility);
// Initial visibility management
manageToolbarAndFabVisibility();
}
/**
* Manage the visibility of toolbar and FAB based on the active fragment.
*/
private void manageToolbarAndFabVisibility(){
boolean hideToolbarAndFab = false;
// Get all active fragments
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for(Fragment fragment : fragments){
if(fragment instanceof FragmentEdit || fragment instanceof LabelListFragment){
hideToolbarAndFab = true;
break;
}
}
if(hideToolbarAndFab){
hideToolbar();
hideFab();
}
else{
showToolbar();
showFab();
}
}
/**
* Find a flashcard by its ID.
*
* @param id The ID of the flashcard.
* @return The Flashcard object if found, else null.
*/
private Flashcard getFlashcardById(String id) {
for (Flashcard flashcard : adapter.getFilteredFlashcards()) {
if (flashcard.getId().equals(id)) {
return flashcard;
}
}
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
this.menu = menu;
toolbar.setOverflowIcon(getDrawable(R.drawable.ic_menu_threedot));
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// Return false to indicate that we have not handled the query submission
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
currentQuery = newText; // Update the current search query
adapter.filter(selectedTag, selectedCategory, currentQuery); // Update the filter
return true;
}
});
// Update menu icon based on view type
updateMenuIcon(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
if (id == R.id.action_night_mode) {
toggleNightMode();
return true;
}
if (id == R.id.action_googlekeepmode) {
sharedPreferencesManager.toggleGoogleKeepMode();
recreate();
return true;
}
if (id == R.id.action_sort) {
ShowPopUpSortMenu(findViewById(R.id.action_sort));
return true;
}
if (id == R.id.action_change_recycleview_layout) {
// Get current view type
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
// Determine new view type
SharedPreferencesManager.ViewType newViewType;
switch (currentViewType) {
case LIST:
newViewType = SharedPreferencesManager.ViewType.GRID;
break;
case GRID:
newViewType = SharedPreferencesManager.ViewType.STAGGERED_GRID;
break;
case STAGGERED_GRID:
default:
newViewType = SharedPreferencesManager.ViewType.LIST;
break;
}
// Set new view type
sharedPreferencesManager.setRecyclerViewLayout(newViewType);
// Update menu icons
updateMenuIcon(menu);
// Apply RecyclerView layout
applyRecyclerViewLayout();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Deletes the selected items from both Firebase and the local list.
*/
private void deleteSelectedItems(){
Set<Integer> selectedPositions = adapter.getSelectedItems();
ArrayList<Flashcard> itemsToDelete = new ArrayList<>();
// Collect items to delete
for(Integer pos : selectedPositions){
itemsToDelete.add(adapter.getFilteredFlashcards().get(pos));
}
// Delete from Firebase and local list
for(Flashcard flashcard : itemsToDelete){
// Delete from Firebase
FirebaseManager.getInstance().deleteFlashcard(flashcard.getId());
// Delete from local list
flashcardList.remove(flashcard);
}
// Update tag and category lists
updateTagAndCategoryLists();
// Update adapter filters
adapter.filter(selectedTag, selectedCategory, currentQuery);
Toast.makeText(this, itemsToDelete.size() + " flashcard(s) deleted.", Toast.LENGTH_SHORT).show();
}
/**
* Toggles the selection state of an item.
* @param position Position of the item to toggle
*/
private void toggleSelection(int position){
adapter.toggleSelection(position);
int count = adapter.getSelectedItemCount();
if(count == 0){
if(actionMode != null){
actionMode.finish();
}
} else {
actionMode.setTitle(count + " selected");
actionMode.invalidate();
}
}
private void toggleNightMode() {
sharedPreferencesManager.toggleNightMode();
onNightModeChanged(!sharedPreferencesManager.isNightModeEnabled());
recreate();
}
/**
* Updates the menu icon based on the current RecyclerView layout.
* @param menu The menu to update
*/
private void updateMenuIcon(Menu menu) {
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
MenuItem item = menu.findItem(R.id.action_change_recycleview_layout);
switch (currentViewType) {
case LIST:
item.setIcon(R.drawable.ic_vertical_list_icon);
break;
case GRID:
item.setIcon(R.drawable.ic_gridview_icon);
break;
case STAGGERED_GRID:
item.setIcon(R.drawable.ic_staggeredgridview_icon); // Ensure this drawable exists
break;
}
}
/**
* Applies the selected layout manager to the RecyclerView.
*/
private void applyRecyclerViewLayout() {
SharedPreferencesManager.ViewType currentViewType = sharedPreferencesManager.getRecyclerViewLayout();
switch (currentViewType) {
case LIST:
recyclerView.setLayoutManager(new LinearLayoutManager(this));
break;
case GRID:
recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); // 2 columns grid
break;
case STAGGERED_GRID:
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); // 2 columns staggered grid
break;
}
adapter.notifyDataSetChanged(); // Notify adapter of changes
}
/**
* Interface to handle back press events in fragments.
*/
public interface OnBackPressedListener {
void onBackPressed();
}
// Helper methods to show/hide toolbar and FAB
public void hideToolbar() {
if (toolbar != null) {
toolbar.setVisibility(View.GONE);
}
}
public void showToolbar() {
if (toolbar != null) {
toolbar.setVisibility(View.VISIBLE);
}
}
public void hideFab() {
if (fab != null) {
fab.hide();
}
}
public void showFab() {
if (fab != null) {
fab.show();
}
}
/**
* Shows a popup menu for sorting options.
* @param anchorView The view to anchor the popup menu to
*/
public void ShowPopUpSortMenu(View anchorView) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, anchorView);
popupMenu.getMenuInflater().inflate(R.menu.sort_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(item -> {
int itemId = item.getItemId();
if (itemId == R.id.sort_alphabetically) {
sortAlphabetically();
return true;
} else if (itemId == R.id.sort_newest) {
sortNewest();
return true;
} else if (itemId == R.id.sort_oldest) {
sortOldest();
return true;
} else if (itemId == R.id.sort_last_updated) {
sortLastUpdated();
return true;
}
return false;
});
popupMenu.show();
}
/**
* Sorts flashcards with pinned items always on top, sorted by the provided comparator.
* @param comparator Comparator to define sorting criteria
*/
private void sortFlashcards(Comparator<Flashcard> comparator) {
Collections.sort(flashcardList, (o1, o2) -> {
// Check pinned status
if (o1.isPinned() && !o2.isPinned()) {
return -1; // o1 before o2
} else if (!o1.isPinned() && o2.isPinned()) {
return 1; // o2 before o1
} else if (o1.isPinned() && o2.isPinned()) {
// If both are pinned, sort by comparator
return comparator.compare(o1, o2);
} else {
// If neither is pinned, sort by comparator
return comparator.compare(o1, o2);
}
});
}
/**
* Sorts flashcards alphabetically by title.
*/
private void sortAlphabetically() {
Comparator<Flashcard> alphabeticalComparator = String::compareToIgnoreCase;
sortFlashcards((o1, o2) -> o1.getTitle().compareToIgnoreCase(o2.getTitle()));
adapter.filter(selectedTag, selectedCategory, currentQuery);
Toast.makeText(this, "Sorted alphabetically.", Toast.LENGTH_SHORT).show();
}
/**
* Sorts flashcards by newest timestamp.
*/
private void sortNewest() {
Comparator<Flashcard> newestComparator = (o1, o2) -> Long.compare(o2.getTimestamp(), o1.getTimestamp());
sortFlashcards(newestComparator);
adapter.filter(selectedTag, selectedCategory, currentQuery);
Toast.makeText(this, "Sorted by newest.", Toast.LENGTH_SHORT).show();
}
/**
* Sorts flashcards by oldest timestamp.
*/
private void sortOldest() {
Comparator<Flashcard> oldestComparator = (o1, o2) -> Long.compare(o1.getTimestamp(), o2.getTimestamp());
sortFlashcards(oldestComparator);
adapter.filter(selectedTag, selectedCategory, currentQuery);
Toast.makeText(this, "Sorted by oldest.", Toast.LENGTH_SHORT).show();
}
/**
* Sorts flashcards by last updated timestamp.
*/
private void sortLastUpdated() {
Comparator<Flashcard> lastUpdatedComparator = (o1, o2) -> Long.compare(o2.getUpdatedAt(), o1.getUpdatedAt());
sortFlashcards(lastUpdatedComparator);
adapter.filter(selectedTag, selectedCategory, currentQuery);
// Optionally, remove the toast if unnecessary
}
/**
* Shows the tag and category selection dialog.
*/
private void showTagAndCategorySelectionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Filter by Category or Tag");
// Prepare display lists
List<String> displayCategories = new ArrayList<>();
for (String category : categoryList) {
int count = categoryCountMap.getOrDefault(category, 0);
displayCategories.add(category + " (" + count + ")");
}
List<String> displayTags = new ArrayList<>();
for (String tag : tagList) {
displayTags.add(tag); // Optionally add counts if desired
}
// Create a combined list with dividers
List<String> combinedList = new ArrayList<>();
if (!displayCategories.isEmpty()) {
combinedList.add("Categories"); // Section header
combinedList.addAll(displayCategories);
}
if (!displayTags.isEmpty()) {
combinedList.add("Tags"); // Section header
combinedList.addAll(displayTags);
}
String[] itemsArray = combinedList.toArray(new String[0]);
builder.setItems(itemsArray, (dialog, which) -> {
String selectedItem = itemsArray[which];
if (selectedItem.equals("Categories") || selectedItem.equals("Tags")) {
// Do nothing when section headers are clicked
return;
}
if (selectedItem.endsWith(")")) {
// It's a category with count
int lastIndex = selectedItem.lastIndexOf("(");
String categoryName = selectedItem.substring(0, lastIndex - 1).trim(); // Remove space before '('
selectedCategory = categoryName;
selectedTag = ""; // Reset tag selection if category is selected
adapter.filter(selectedTag, selectedCategory, currentQuery);
Toast.makeText(MainActivity.this, "Category \"" + categoryName + "\" selected.", Toast.LENGTH_SHORT).show();
} else {
// It's a tag
selectedTag = selectedItem;
selectedCategory = ""; // Reset category selection if tag is selected
adapter.filter(selectedTag, selectedCategory, currentQuery);
Toast.makeText(MainActivity.this, "Tag \"" + selectedTag + "\" selected.", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", (dialog, which) -> {
dialog.dismiss();
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Updates both tag and category lists by recounting from flashcardList.
*/
private void updateTagAndCategoryLists() {
tagList.clear();
categoryCountMap.clear();
categoryList.clear();
for (Flashcard flashcard : flashcardList) {
// Collect tags
if (flashcard.getHashtags() != null) {
for (String tag : flashcard.getHashtags()) {
if (tag != null && !tag.trim().isEmpty()) {
tagList.add(tag.trim());
}
}
}
// Collect categories
String category = flashcard.getCategory();
if (category != null && !category.trim().isEmpty()) {
category = category.trim();
categoryCountMap.put(category, categoryCountMap.getOrDefault(category, 0) + 1);
}
}
// Process unique tags
Set<String> uniqueTags = new HashSet<>(tagList);
tagList.clear();
tagList.addAll(uniqueTags);
Collections.sort(tagList); // Optional: Sort alphabetically
// Process unique categories
categoryList.addAll(categoryCountMap.keySet());
Collections.sort(categoryList); // Optional: Sort alphabetically
}
/**
* Updates a flashcard's data in Firebase.
*
* @param id Flashcard ID.
* @param category Category name.
* @param title Title.
* @param content Content.
* @param favorite Favorite status.
* @param pinned Pinned status.
* @param hashtags Hashtag list.
* @param backgroundColor Background color in HEX string.
*/
private void updateFlashcard(String id, String category, String title, String content, boolean favorite, boolean pinned, List<String> hashtags, String backgroundColor) {
Map<String, Object> updates = new HashMap<>();
updates.put("category", category);
updates.put("title", title);
updates.put("content", content);
updates.put("favorite", favorite);
updates.put("pinned", pinned);
updates.put("hashtags", hashtags);
updates.put("backgroundColor", backgroundColor);
long currentTimestamp = System.currentTimeMillis();
updates.put("updatedAt", currentTimestamp);
FirebaseManager.getInstance().updateFlashcard(id, updates);
}
/**
* Updates the menu item icons based on selection states.
* @param item The menu item to update
* @param allSelected Whether all items are selected
* @param hasSelected Whether some items are selected
* @param filledIcon Icon resource for filled state
* @param outlinedIcon Icon resource for outlined state
*/
private void updateMenuItemIcon(MenuItem item, boolean allSelected, boolean hasSelected, int filledIcon, int outlinedIcon) {
if (allSelected) {
item.setChecked(true);
item.setIcon(filledIcon);
} else if (hasSelected) {
item.setChecked(false); // Partial selection can be indicated differently if desired
item.setIcon(outlinedIcon);
} else {
item.setChecked(false);
item.setIcon(outlinedIcon);
}
}
/**
* Shows the color palette dialog to change flashcard colors.
*/
public void showColorPaletteDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = LayoutInflater.from(this).inflate(R.layout.color_picker_dialog, null);
builder.setView(dialogView);
GridLayout colorGrid = dialogView.findViewById(R.id.colorGrid);
boolean isNightMode = sharedPreferencesManager.isNightModeEnabled();
final int[] colors;
if (isNightMode) {
// Dark mode colors
colors= new int[]{
R.drawable.ic_clear_color,
0xFF232531, // Dark Blue
0xFF482E5B, // Dark Purple
0xFF264D3B, // Dark Green
0xFF274255, // Medium Blue
0xFF256476, // Light Blue
0xFF232530, // Dark Gray
0xFF692A18, // Dark Brown
0xFF76172D, // Dark Red
0xFF232428, // Dark Black
0xFF4B443A // Medium Brown
};
} else {
// Light mode colors
colors = new int[]{
R.drawable.ic_clear_color,
0xFFD3D6E3, // Light Blue
0xFFE6D9ED, // Light Purple
0xFFD9E6DD, // Light Green
0xFFD9E1E6, // Medium Blue
0xFFD9E6E9, // Light Blue
0xFFD3D6E3, // Light Gray
0xFFE6D9D3, // Light Brown
0xFFE6D3D9, // Light Red
0xFFD3D6E3, // Light Black (Grayish)
0xFFE6E3D9 // Medium Brown
};
}
AlertDialog dialog = builder.create();
// First color item: Clear color option
View firstColorItem = LayoutInflater.from(this).inflate(R.layout.color_item, null);
ImageView firstColorIconImgView = firstColorItem.findViewById(R.id.colorIcon);
firstColorIconImgView.setImageResource(colors[0]);
firstColorItem.setOnClickListener(v -> {
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.getFilteredFlashcards().get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), flashcard.isPinned(), flashcard.getHashtags(), "");
}
dialog.dismiss();
});
colorGrid.addView(firstColorItem, 0);
// Add other color items
for (int i = 1; i < colors.length; i++) {
final int color = colors[i];
View itemView = LayoutInflater.from(this).inflate(R.layout.color_item, null);
ImageView colorIcon = itemView.findViewById(R.id.colorIcon);
colorIcon.setBackgroundColor(color);
itemView.setOnClickListener(v -> {
String chosencolor = String.format("#%06X", (0xFFFFFF & color));
for (Integer position : adapter.getSelectedItems()) {
Flashcard flashcard = adapter.getFilteredFlashcards().get(position);
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), flashcard.isPinned(), flashcard.getHashtags(), chosencolor);
}
dialog.dismiss();
});
colorGrid.addView(itemView);
}
dialog.show();
}
/**
* Called when night mode is toggled. Updates flashcard colors accordingly.
* @param isNightMode True if night mode is enabled, false otherwise
*/
public void onNightModeChanged(boolean isNightMode) {
for (Flashcard flashcard : flashcardList) {
String backgroundColor = flashcard.getBackgroundColor();
if (backgroundColor != null && !backgroundColor.isEmpty()) {
int color = Color.parseColor(backgroundColor);
int tintColor;
if (isNightMode) {
tintColor = reverseColorMap.getOrDefault(color, color);
} else {
tintColor = colorMap.getOrDefault(color, color);
}
flashcard.setBackgroundColor(String.format("#%06X", (0xFFFFFF & tintColor)));
updateFlashcard(flashcard.getId(), flashcard.getCategory(), flashcard.getTitle(), flashcard.getContent(), flashcard.isFavorite(), flashcard.isPinned(), flashcard.getHashtags(), flashcard.getBackgroundColor());
}
}
adapter.notifyDataSetChanged();
}
}