android tutorial listview에서 sd 카드의 파일 삭제




flutter widget size (2)

이렇게하면 돼.

File list[]; 만들기 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;
                  }
              });

사용자가 더 이상 필요없는 파일을 삭제할 수있게하기 위해 SD 카드에있는 디렉토리의 파일 목록을 보여주는 listview가 있습니다. 이제는 각 파일의 경로를 검색하는 방법을 찾고, 어떻게 든 목록보기의 각 항목에 연결하고 사용자가 파일을 삭제할 수있게해야합니다. 항목을 길게 클릭하면 팝업 대화 상자가 나타납니다. 그 사람이 "확인"버튼을 누르면 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
    }

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




io