2013-08-31 75 views
1

要让用户删除不再需要的文件,我有一个列表视图,其中显示SD卡上目录中的文件列表。我现在需要找到一种方法来检索每个文件的路径,以某种方式将它链接到它在listview中的相应项目,并让用户删除该文件。当一个项目被长按时,我弹出一个对话框;我现在需要在个人按下“OK”按钮后删除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 
    } 

回答

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; 
        } 
       }); 
+0

好吧,但我在困惑什么是 “我” 在括号内 “名单[I] .delete();”是什么? – ThatGuyThere

+0

使用列表[pos] .delete(); –

+0

我已经完成了这个操作,它显示了在用户按下“确定”之后被删除的文件,但是当我返回并重新启动活动时,该文件仍然显示在列表中,即使它显示被删除之前。 – ThatGuyThere

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()); 
    } 
} 
+0

我很困惑“dbuser”和“checkItem”是什么? – ThatGuyThere

+0

在列表视图中,我有checkboxes,其中checkitem是一个数组列表,包含检查项目的值到要删除的列表中。 –

+0

我也使用要删除的文件名...在_recordList中获取文件,然后进入for循环,每个文件都将从外部存储中删除。 –