Reputation: 329
I want to create a reset button in Settings. When I'll press this button, all data and shared preferences must be deleted like when I press to Clear data
in Manage applications
option.
Is there any way to do that?
public class Settings extends MainActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public static void delete(File file, boolean deleteDir)
{
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
delete(f, true);
}
}
if (deleteDir) {
file.delete();
}
} else {
file.delete();
}
}
public static void clearData(Context context)
{
File files = context.getDir("tmp", Context.MODE_PRIVATE);
delete(files.getParentFile(), false);
}
public void OnClickReset(View v)
{
clearData(this);
}
}
Upvotes: 1
Views: 3137
Reputation: 5419
I'm not sure, but I think you can use method Context.getFilesDir()
. It returns File
object which refers on internal app directory.
After that you can access to parent directory and delete all content of it.
EDITED:
Well, this code works:
File AppUtils.java
import android.content.Context;
import java.io.File;
public class AppUtils {
public static void delete(File file, boolean deleteDir) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
delete(f, true);
}
}
if (deleteDir) {
file.delete();
}
} else {
file.delete();
}
}
public static void clearData(Context context) {
File files = context.getDir("tmp", Context.MODE_PRIVATE);
delete(files.getParentFile(), false);
}
}
But I use method getDir()
instead of getFilesDir()
because second one may return null
.
NOTE: If you will have opened SharedPreferences.Editor
, then you won't delete it! Also, opened database or any opened file descriptor may cause same issue.
Upvotes: 2