1

为了让用户删除他们不再需要的文件,我有一个列表视图,它显示位于 SD 卡上的目录中的文件列表。我现在需要找到一种方法来检索每个文件的路径,以某种方式将其链接到列表视图中的相应项目并让用户删除该文件。我做了一个对话框,当一个项目被长按时会弹出;我现在需要在此人按下“确定”按钮后删除 SD 卡上的文件。这些文件都是在不同的活动中创建的,所以我假设必须通过意图传递一些东西。

ReadFilesFromDirectory.java

public class ReadFilesFromPath extends Activity {
/** Called when the activity is first created. */
List<String> myList;
File file;
ListView listview;
ArrayAdapter<String> adapter;
String value;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recordinglist);
    Intent intent = getIntent();
    value = intent.getStringExtra("path"); //if it's a string you stored.
    listview = (ListView) findViewById(R.id.recordlist);
    myList = new ArrayList<String>();
    onitemclick();
    File directory = Environment.getExternalStorageDirectory();
    file = new File( directory + "/" + "Recordings" );
    File list[] = file.listFiles();

    for( int i=0; i< list.length; i++)
    {
            myList.add( list[i].getName() );
    }
    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, myList);
    listview.setAdapter(adapter); //Set all the file in the list.
    longclick();
}

    public void longclick() {
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int pos, long arg3) {
                AlertDialog.Builder adb=new AlertDialog.Builder(ReadFilesFromPath.this); //alert for each time an item is pressed
                  adb.setTitle("Delete?");
                  adb.setMessage("Are you sure you want to delete this recording?");
                  final int positionToRemove = pos;
                  adb.setNegativeButton("Cancel", null);
                  adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {

                      public void onClick(DialogInterface dialog, int which) {
                          listview.animate().setDuration(500).alpha(0) //animates a smooth deletion animation
                            .withEndAction(new Runnable() {
                              @Override
                              public void run() {

                           //DELETE THE FILE HERE

                                Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
                                myList.remove(positionToRemove); //removes the selected item
                                adapter.notifyDataSetChanged(); //tells the adapter to delete it
                                listview.setAlpha(1); 
                              }
                            }); 
                      }});
                  adb.show();
                  return true;
                  }
              });

            } 

public void onitemclick() {

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

              @Override
              public void onItemClick(AdapterView<?> parent, final View view,
                  int position, long id) {


    }
        }); 

}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}



}

我将文件的数据保存在这样的不同活动中(类中有更多方法,但它们不影响文件的保存):

public class MainActivity extends Activity {

MediaRecorder recorder;
File audiofile = null, file, directory;
private static final String TAG = "SoundRecordingActivity";
Button startButton, stopButton, openfiles, recordingbtn, delete, aboutbtn, exitbtn;
TextView welcometext;
SimpleDateFormat df;
String formattedDate, name, value, pathToExternalStorage;
String[] toastMessages;
File appDirectory, filetodelete;
int randomMsgIndex, number;
CheckBox mp4;
ContentValues values;
Uri base, newUri;
Boolean recordingstarted;
List<String> myList;
ListView listview;
ArrayAdapter<String> adapter;
private MenuDrawer mDrawer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    mDrawer = MenuDrawer.attach(this, Position.BOTTOM);
    mDrawer.setContentView(R.layout.activity_main);
    mDrawer.setMenuView(R.layout.leftmenu);
    Calendar c = Calendar.getInstance();
    df = new SimpleDateFormat("hh:mm:ss");
    formattedDate = df.format(c.getTime());
    name = "Recording";
    listview = (ListView)findViewById(R.id.recordlist);
    exitbtn = (Button)findViewById(R.id.exitbtn);
    openfiles = (Button)findViewById(R.id.openfilesbtn);
    aboutbtn = (Button)findViewById(R.id.aboutbtn);
    startButton = (Button) findViewById(R.id.start);

    stopButton = (Button) findViewById(R.id.stop);
    pathToExternalStorage = Environment.getExternalStorageDirectory().toString();
    appDirectory = new File(pathToExternalStorage + "/" + "Recordify");

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/robothin.ttf");
    welcometext = (TextView)findViewById(R.id.welcomeandtimetext);
    welcometext.setTypeface(myTypeface);
    onclicks();
    startandstop();

} 


protected void addRecordingToMediaLibrary() {
        values = new ContentValues(4);
        values.put(MediaStore.Audio.Media.TITLE, name); //"audio" + audiofile.getName()
        values.put(MediaStore.Audio.Media.MIME_TYPE, "video/mp4"); //sets the type to be a mp4 video file, despite being audio
        values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
        ContentResolver contentResolver = getContentResolver();
        base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        newUri = contentResolver.insert(base, values);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
        welcometext.setText("Saved as " + audiofile); //teling users what name of file is called
    }
4

2 回答 2

0

这样做

File list[];全球化_

listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    final int pos, long arg3) {
                AlertDialog.Builder adb=new AlertDialog.Builder(ReadFilesFromPath.this); //alert for each time an item is pressed
                  adb.setTitle("Delete?");
                  adb.setMessage("Are you sure you want to delete this recording?");
                  final int positionToRemove = pos;
                  adb.setNegativeButton("Cancel", null);
                  adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {

                      public void onClick(DialogInterface dialog, int which) {
                          listview.animate().setDuration(500).alpha(0) //animates a smooth deletion animation
                            .withEndAction(new Runnable() {
                              @Override
                              public void run() {

                           //DELETE THE FILE HERE

                                try{
                                  list[pos].delete();
                                }catch(Exception e){
                                }



                                Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
                                myList.remove(positionToRemove); //removes the selected item
                                adapter.notifyDataSetChanged(); //tells the adapter to delete it
                                listview.setAlpha(1); 
                              }
                            }); 
                      }});
                  adb.show();
                  return true;
                  }
              });
于 2013-08-31T07:08:29.970 回答
0
final Dialog deleteDialog = new Dialog(Record.this);
            deleteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            deleteDialog.setContentView(R.layout.newdeletedialog);
            TextView text1 = (TextView) deleteDialog
                    .findViewById(R.id.textValue);
            Typeface tf1 = Typeface.createFromAsset(getAssets(),
                    "fonts/Roboto-Regular.ttf");
            text1.setTypeface(tf1);

            Button deleteok = (Button) deleteDialog
                    .findViewById(R.id.deleteOk);
            Button deletecancel = (Button) deleteDialog
                    .findViewById(R.id.deleteCancel);
            deleteok.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    delete.setBackgroundResource(R.drawable.delete);
                    String[] _file = new String[] {};
                    String[] deleted = new String[] {};
                    File baseDir = Environment
                            .getExternalStorageDirectory();

                    for (int i = 0; i < checkItem.size(); i++) {
                        deleted = checkItem.toArray(new String[checkItem
                                .size()]);

                    }
                    for (int k = 0; k < _recordList.size(); k++) {
                        _file = _recordList.toArray(new String[_recordList
                                .size()]);
                    }
                    for (int j = 0; j < _file.length; j++) {
                        dbuser.open();
                        dbuser.DeleteItem(_file[j]);
                        dbuser.close();
                    }
                    for (int l = 0; l < _file.length; l++) {

                        try {
                            _file[l] = baseDir + "/Recording/" + _file[l];

                            datadelete(_file[l]);
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }


public void datadelete(String inputPath) throws FileNotFoundException {
    try {
        // delete the original file
        new File(inputPath).delete();

    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
}
于 2013-08-31T10:17:39.117 回答