GIRIDHARAN
GIRIDHARAN

Reputation: 169

Unable to Clear Cache memory programmatically Android

I have tried to clear cache memory through button in my application by using below code.
activity_main.xml

 <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:id="@+id/button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete Cache"
        android:id="@+id/button2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retrive Data"
        android:id="@+id/button3" />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity  {
TextView t1;
EditText et1;
Button b1,b2,b3;
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
SharedPreferences.Editor editor;
private static MainActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    settings = getSharedPreferences(MainActivity.PREFS_NAME, 0);
    editor= settings.edit();
    instance=this;
    t1=(TextView)findViewById(R.id.textView);
    et1=(EditText)findViewById(R.id.editText);
    b1=(Button)findViewById(R.id.button);
    b2=(Button)findViewById(R.id.button2);
    b3=(Button)findViewById(R.id.button3);
    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editor.putString("editText",et1.getText().toString());
            editor.commit();
            t1.setText(settings.getString("editText",null));
        }
    });
    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            t1.setText("");
            MainActivity.getInstance().clearApplicationData();
                        }
    });
    b3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            t1.setText(settings.getString("editText",null));
        }
    });
}
public static MainActivity getInstance(){ return instance;}
public void clearApplicationData(){
        File cache= getCacheDir();
        File appDir=new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s: children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir,s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/ " + s +" DELETED");
                }
            }
        }
}
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();
    }
    else {
        return false;
    }
}}

Explanation:
While clicking Save button the value typed in EditText will be saved in Shared Preference.While clicking Delete Cache written code for deleting cache memory with Refer 1, Refer 2.While clicking Retrive value stored in Shared Preference will be retrieved and displayed in TextView.

Issue: While clicking the Delete Cache in my logcat its showing that cache memory deleted and shared_prefs deleted but my cache memory size not reduced. While clicking Retrive the value from Shared Preference is retriving and showing up in TextView but value should be deleted.

My logcat:

01-09 17:02:26.872 24290-24290/? I/TAG: File /data/data/APP_PACKAGE/ cache DELETED
01-09 17:02:26.872 24290-24290/? I/TAG: File /data/data/APP_PACKAGE/ shared_prefs DELETED

What have I missed?

Upvotes: 1

Views: 1621

Answers (1)

Sasi Kumar
Sasi Kumar

Reputation: 13313

onStop() and onDestroy() methods include into your Activity. Your Activity onDestroy() add following code

 @Override
  protected void onStop(){
  super.onStop();
   }
 // after the OnStop() state


  @Override
  protected void onDestroy() {
  super.onDestroy();
  try {
     trimCache(this);
      } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     }
   }

and then add following methods

 public static void trimCache(Context context) {
  try {
     File dir = context.getCacheDir();
     if (dir != null && dir.isDirectory()) {
        deleteDir(dir);
     }
  } catch (Exception e) {
     // TODO: handle exception
  }
 }

 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;
        }
     }
  }

  // The directory is now empty so delete it
  return dir.delete();
 }

Upvotes: 4

Related Questions