0

According to this post , I want to delete the cache of the program by clicking on some element in the navigation drawer.

I've tried this snippet on the MainActivity.java for deleting the cache in the onNavigationItemSelectedListener but it's not working.

my onNavigationItemSelectedListener in the onCreate() method

 //-------------------------------------- find navigation view
    NavigationView navigationView = (NavigationView)findViewById(R.id.xmlNavigation);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            int itemId = menuItem.getItemId();
            if(itemId == R.id.star){

                  ===>  deleteCache(MainActivity.this);
                  ===>   deleteDir(MainActivity.this.getCacheDir());

               Toast.makeText(MainActivity.this , "cache is deleted!" , Toast.LENGTH_SHORT).show();
            }
            menuItem.setChecked(true);
            mDrawerLayout.closeDrawers();
            //Toast.makeText(MainActivity.this , menuItem.getTitle() , Toast.LENGTH_SHORT).show();
            return true;
        }
    });


}

and this snippet out of onCreate() and in the MainActivity.java:

///====================================================== snippet for deleting the cache

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
        }
    } catch (Exception e) {}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}

///====================================================== #snippet for deleting the cache
Community
  • 1
  • 1
kiana rahimi
  • 246
  • 4
  • 16
  • It would be useful if you described what happens more. Try to run your activity with debug mode and set breakpoints to see where your code stops or what code is executed and what is not executed. – mdzeko Dec 15 '15 at 13:43
  • Thank you mdzeko for your , answer , in your opinion is it right my method for deleting the cache ? – kiana rahimi Dec 15 '15 at 13:46
  • No problem, it's not an answer realy :). At first glance, I see nothing wrong with the code. You should also check if you requested required permission in the manifest – mdzeko Dec 15 '15 at 13:50

0 Answers0