我正在尝试擦除外部SdCard中存在的所有文件。
我没有得到我的代码无效的地方。
这些是我的档案......
活性-main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button android:id="@+id/wipe_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Wipe the SD card." />
<TextView android:id="@+id/path"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="@+id/file"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
WipeSdActivity.java
package com.example.wipe_sd;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class WipeSDActivity extends Activity {
private int mDeletedFiles = 0;
private int mDeletedFolders = 0;
private TextView mDirectoryTextView;
private TextView mFileTextView;
private List<String> mUndeleteableFiles;
MyAsyncTask test;
public Button btnwipe_sd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wipe_sd);
btnwipe_sd = (Button)findViewById(R.id.wipe_button);
test = new MyAsyncTask();
File[] arrayOfFile = new File[1];
arrayOfFile[0] = new File(Environment.getExternalStorageDirectory().getPath());
test.execute(arrayOfFile);
btnwipe_sd.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
new AlertDialog.Builder(WipeSDActivity.this).setCancelable(true)
.setMessage("This will attempt to wipe all directories and files on your SD card.")
.setPositiveButton("WIPE", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
}).setNegativeButton("NO!", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
}).show();
}
});
this.mDirectoryTextView = ((TextView)findViewById(R.id.path));
this.mFileTextView = ((TextView)findViewById(R.id.file));
this.mUndeleteableFiles = new ArrayList();
}
public class MyAsyncTask extends AsyncTask<File,Integer,Integer>{
protected Integer doInBackground(File[] ArrayOfFile) {
// TODO Auto-generated method stub
int i = 0;
progressivelyDelete(ArrayOfFile[0]);
if (ArrayOfFile[0].exists())
i = ArrayOfFile[0].listFiles().length;
return Integer.valueOf(i);
}
private void progressivelyDelete(File sd_File) {
// TODO Auto-generated method stub
if (sd_File == null);
while (true)
{
if (sd_File.isDirectory())
{
updateDirectory(sd_File.getPath());
File[] arrayOfFile = sd_File.listFiles();
int i = arrayOfFile.length;
int j = 0;
if (j < i)
{
File msd_File = arrayOfFile[j];
if (msd_File.canWrite())
progressivelyDelete(msd_File);
while (true)
{
j++;
break;
}
WipeSDActivity.this.mUndeleteableFiles.add(msd_File.getAbsolutePath());
}
sd_File.delete();
}
else
{
sd_File.delete();
updateFile(sd_File.getName());
}
}
}
private void updateFile(final String paramString) {
// TODO Auto-generated method stub
Log.d("SdWipe", "File - " + paramString);
WipeSDActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
TextView localfile_TextView = WipeSDActivity.this.mFileTextView;
Object[] arrayofObject = new Object[1];
arrayofObject[0] = paramString;
}
});
}
private void updateDirectory(final String paramString) {
// TODO Auto-generated method stub
Log.d("SdWipe", "Folder - " + paramString);
WipeSDActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
TextView localdir_TextView = WipeSDActivity.this.mDirectoryTextView;
Object[] arrayOfObject = new Object[1];
arrayOfObject[0] = paramString;
localdir_TextView.setText(String.format("Currently processing\n%s", arrayOfObject));
}
});
}
protected void onPostExecute(Integer paramInteger)
{
TextView dir_textview = WipeSDActivity.this.mDirectoryTextView;
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = Integer.valueOf(WipeSDActivity.this.mDeletedFolders);
arrayOfObject[1] = Integer.valueOf(WipeSDActivity.this.mDeletedFiles);
dir_textview.setText(String.format("Done\n%s folders deleted\n%s files deleted",arrayOfObject));
StringBuilder localStringBuilder = new StringBuilder();
Iterator localIterator = WipeSDActivity.this.mUndeleteableFiles.iterator();
while(localIterator.hasNext())
{
String str = (String) localIterator.next();
localStringBuilder.append(str + "\n");
}
WipeSDActivity.this.mFileTextView.setText(paramInteger + "files left on SD Card:\n" + localStringBuilder);
}
protected void onPreExecute()
{
WipeSDActivity.this.mUndeleteableFiles.clear();
}
}
}
的Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wipe_sd"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.wipe_sd.WipeSDActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
我得到的Log Cat错误是:
02-08 16:47:13.460: E/AndroidRuntime(270): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.wipe_sd/com.example.wipe_sd.WipeSDActivity}: java.lang.NullPointerException
02-08 16:47:13.460: E/AndroidRuntime(270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.os.Looper.loop(Looper.java:123)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-08 16:47:13.460: E/AndroidRuntime(270): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 16:47:13.460: E/AndroidRuntime(270): at java.lang.reflect.Method.invoke(Method.java:521)
02-08 16:47:13.460: E/AndroidRuntime(270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-08 16:47:13.460: E/AndroidRuntime(270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-08 16:47:13.460: E/AndroidRuntime(270): at dalvik.system.NativeStart.main(Native Method)
02-08 16:47:13.460: E/AndroidRuntime(270): Caused by: java.lang.NullPointerException
02-08 16:47:13.460: E/AndroidRuntime(270): at com.example.wipe_sd.WipeSDActivity$MyAsyncTask.onPreExecute(WipeSDActivity.java:204)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.os.AsyncTask.execute(AsyncTask.java:391)
02-08 16:47:13.460: E/AndroidRuntime(270): at com.example.wipe_sd.WipeSDActivity.onCreate(WipeSDActivity.java:44)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-08 16:47:13.460: E/AndroidRuntime(270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-08 16:47:13.460: E/AndroidRuntime(270): ... 11 more
答案 0 :(得分:2)
这里我修改了 WipeSDActivity.java 类。请检查并告诉我。希望它对你有所帮助。感谢。
import java.io.File;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class WipeSDActivity extends Activity {
private static ProgressDialog progressBar;
private static int progressBarStatus = 0;
private static Handler progressBarHandler = new Handler();
public Button btnwipe_sd;
private int fileCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sd_card);
btnwipe_sd = (Button)findViewById(R.id.wipe_button);
btnwipe_sd.setOnClickListener(new OnClickListener()
{
public void onClick(final View view)
{
new AlertDialog.Builder(WipeSDActivity.this).setCancelable(true)
.setMessage("This will attempt to wipe all directories and files on your SD card.")
.setPositiveButton("WIPE", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
FormatSDCard(view);
}
}).setNegativeButton("NO!", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
}).show();
}
});
}
public void FormatSDCard(View v){
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(false);
progressBar.setMessage("File deleting ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
//fileCount = 0;
// process some tasks
progressBarStatus = wipingSdcard();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is deleted,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}
public int wipingSdcard() {
File deleteMatchingFile = new File(Environment
.getExternalStorageDirectory().toString());
try {
File[] filenames = deleteMatchingFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
fileCount++;
progressBarStatus = fileCount;
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
} else {
deleteMatchingFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
return fileCount;
}
private void wipeDirectory(String name) {
File directoryFile = new File(name);
File[] filenames = directoryFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
}
} else {
directoryFile.delete();
}
}
}
如果您使用的是&gt; 1.6 SDK
,则必须同意 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
AndroidManifest.xml 文件中的