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