从列表视图删除SD卡上的文件 [英] Delete file on sd card from a listview

查看:123
本文介绍了从列表视图删除SD卡上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要允许用户删除他们不再想要的文件,我有一个列表视图显示的文件位于SD卡上的目录列表。我现在需要找到一种方法来检索每个文件的路径,不知它在列表视图链接到它的各个项目,并让用户删除该文件。我做了弹出当一个项目是长期点击一个对话框;我现在需要删除SD卡上的文件的人$ P $后psses确定按钮。这些文件在不同的活动中的所有创建的,所以我假设的东西都将通过一个意图传递。

ReadFilesFromDirectory.java

 公共类ReadFilesFromPath延伸活动{
/ **当第一次创建活动调用。 * /
清单<串GT; myList中;
档案文件;
ListView控件列表视图;
ArrayAdapter<串GT;适配器;
字符串值;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.recordinglist);
    意向意图= getIntent();
    值= intent.getStringExtra(路径); //如果它是一个字符串,你保存。
    列表视图=(ListView控件)findViewById(R.id.recordlist);
    myList中=新的ArrayList<串GT;();
    onitemclick();
    文件目录= Environment.getExternalStorageDirectory();
    文件=新的文件(目录+/+记录);
    文件列表[] = file.listFiles();    的for(int i = 0; I< List.length的数字,我++)
    {
            myList.add(名单[I] .getName());
    }
    适配器=新ArrayAdapter<串GT;(这一点,
            android.R.layout.simple_list_item_1,android.R.id.text1,myList中);
    listview.setAdapter(适配器); //设置所有的文件在列表中。
    longclick();
}    公共无效longclick(){
        listview.setOnItemLongClickListener(新AdapterView.OnItemLongClickListener(){            公共布尔onItemLongClick(适配器视图<>为arg0,视图V,
                    INT POS,长ARG3){
                AlertDialog.Builder ADB =新AlertDialog.Builder(ReadFilesFromPath.this); //每次警报的项目是pressed
                  adb.setTitle(删除?);
                  adb.setMessage(你确定要删除这个记录?);
                  最终诠释positionToRemove = POS;
                  adb.setNegativeButton(取消,NULL);
                  adb.setPositiveButton(OK,新AlertDialog.OnClickListener(){                      公共无效的onClick(DialogInterface对话,诠释它){
                          listview.animate()。setDuration(500)阿尔法(0)//动画光滑删除动画
                            .withEndAction(新的Runnable(){
                              @覆盖
                              公共无效的run(){                           //此处删除文件                                Toast.makeText(getApplicationContext()已删除,Toast.LENGTH_SHORT).show();
                                myList.remove(positionToRemove); //删除所选项目
                                adapter.notifyDataSetChanged(); //告诉适配器将其删除
                                listview.setAlpha(1);
                              }
                            });
                      }});
                  adb.show();
                  返回true;
                  }
              });            }公共无效onitemclick(){        listview.setOnItemClickListener(新AdapterView.OnItemClickListener(){              @覆盖
              公共无效onItemClick(适配器视图<>母公司,最终视图来看,
                  INT位置,长的id){
    }
        });}@覆盖
公共无效onBack pressed(){
    // TODO自动生成方法存根
    super.onBack pressed();
    overridePendingTransition(R.anim.push_right_in,R.anim.push_right_out);
}}

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

 公共类MainActivity延伸活动{MediaRecorder记录;
文件的AudioFile = NULL,文件,目录;
私有静态最后弦乐TAG =SoundRecordingActivity;
按钮startButton,STOPBUTTON,openFiles散,recordingbtn,删除,aboutbtn,exitbtn;
TextView的welcometext;
SimpleDateFormat的DF;
串formattedDate,名称,价值,pathToExternalStorage;
的String [] toastMessages;
文件appDirectory,filetodelete;
INT randomMsgIndex,数量;
复选框MP4;
ContentValues​​值;
乌里基地,newUri;
布尔recordingstarted;
清单<串GT; myList中;
ListView控件列表视图;
ArrayAdapter<串GT;适配器;
私人MenuDrawer mDrawer;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    mDrawer = MenuDrawer.attach(这一点,Position.BOTTOM);
    mDrawer.setContentView(R.layout.activity_main);
    mDrawer.setMenuView(R.layout.leftmenu);
    日历C = Calendar.getInstance();
    DF =新的SimpleDateFormat(HH:MM:SS);
    formattedDate = df.format(c.getTime());
    NAME =录制;
    列表视图=(ListView控件)findViewById(R.id.recordlist);
    exitbtn =(按钮)findViewById(R.id.exitbtn);
    openFiles散=(按钮)findViewById(R.id.openfilesbtn);
    aboutbtn =(按钮)findViewById(R.id.aboutbtn);
    startButton =(按钮)findViewById(R.id.start);    STOPBUTTON =(按钮)findViewById(R.id.stop);
    。pathToExternalStorage = Environment.getExternalStorageDirectory()的toString();
    appDirectory =新的文件(pathToExternalStorage +/+Recordify);    字体myTypeface = Typeface.createFromAsset(getAssets(),字体/ robothin.ttf);
    welcometext =(的TextView)findViewById(R.id.welcomeandtimetext);
    welcometext.setTypeface(myTypeface);
    onclicks();
    startandstop();}
保护无效addRecordingToMediaLibrary(){
        值=新ContentValues​​(4);
        values​​.put(MediaStore.Audio.Media.TITLE,名); //音频+ audiofile.getName()
        values​​.put(MediaStore.Audio.Media.MIME_TYPE,视频/ MP4); //设置类型是一个MP4的视频文件,尽管是音频
        values​​.put(MediaStore.Audio.Media.DATA,audiofile.getAbsolutePath());
        ContentResolver的ContentResolver的= getContentResolver();
        基地= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        newUri = contentResolver.insert(基地,价值观);
        sendBroadcast(新意图(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,newUri));
        welcometext.setText(保存为+ audiofile的); //特灵叫什么名字文件的用户
    }


解决方案

 最后一个对话框deleteDialog =新的对话框(Record.this);
            deleteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            deleteDialog.setContentView(R.layout.newdeletedialog);
            TextView的文本1 =(TextView中)deleteDialog
                    .findViewById(R.id.textValue);
            字体TF1 = Typeface.createFromAsset(getAssets()
                    字体/的Roboto-Regular.ttf);
            text1.setTypeface(TF1);            按钮deleteok =(按钮)deleteDialog
                    .findViewById(R.id.deleteOk);
            按钮deletecancel =(按钮)deleteDialog
                    .findViewById(R.id.deleteCancel);
            deleteok.setOnClickListener(新View.OnClickListener(){                @覆盖
                公共无效的onClick(查看为arg0){
                    // TODO自动生成方法存根
                    delete.setBackgroundResource(R.drawable.delete);
                    的String [] = _file新的String [] {};
                    的String [] =删除新的String [] {};
                    文件BASEDIR =环境
                            .getExternalStorageDirectory();                    的for(int i = 0; I< checkItem.size();我++){
                        删除= checkItem.toArray(新的String [checkItem
                                。尺寸()​​]);                    }
                    对于(INT K = 0; K< _recordList.size(); K ++){
                        _file = _recordList.toArray(新的String [_recordList
                                。尺寸()​​]);
                    }
                    对于(INT J = 0; J< _file.length; J ++){
                        dbuser.open();
                        dbuser.DeleteItem(_file [J]);
                        dbuser.close();
                    }
                    为(int类型l = 0; L&下; _file.length:L ++){                        尝试{
                            _file [1] = BASEDIR +/录音/+ _file [L]                            (_file [L])datadelete;
                        }赶上(FileNotFoundException异常五){
                            // TODO自动生成catch块
                            e.printStackTrace();
                        }
                    }
公共无效datadelete(字符串inputPath)抛出FileNotFoundException异常{
    尝试{
        //删除原始文件
        新的文件(inputPath).delete();    }赶上(例外五){
        Log.e(标签,e.getMessage());
    }
}

To let users delete files they no longer want, I have a listview that shows a list of files in a directory located on the SD card. I now need to find a way to retrieve the path of each file, somehow link it to it's respective item in the listview and let the user delete the file. I've made a dialog box that pops up when an item is long-clicked; I now need to delete the file on the SD card after the person presses the "OK" button. The files are all created in a different activity, so I'm assuming something will have to be passed via an intent.

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



}

I save the data for the files in a different activity like this (there are more methods in the class, but they don't affect the saving of files):

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
    }

解决方案

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

这篇关于从列表视图删除SD卡上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆