vuelven tarjeta puedo porque movil mover memoria error eliminar como celular borrar archivos archivo aplicaciones aparecer ala activar android listview io

android - puedo - Eliminar archivo en tarjeta SD desde una lista



porque no puedo borrar archivos de mi celular (2)

HAGA ESTO

Hacer File list[]; global

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

Para permitir a los usuarios eliminar archivos que ya no desean, tengo una vista de lista que muestra una lista de archivos en un directorio ubicado en la tarjeta SD. Ahora necesito encontrar una manera de recuperar la ruta de acceso de cada archivo, de alguna manera vincularlo con su elemento respectivo en la vista de lista y dejar que el usuario elimine el archivo. He creado un cuadro de diálogo que aparece cuando se hace clic largo en un elemento; Ahora necesito eliminar el archivo en la tarjeta SD después de que la persona presiona el botón "Aceptar". Todos los archivos se crean en una actividad diferente, así que supongo que algo tendrá que pasar a través de un intento.

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

Guardo los datos para los archivos en una actividad diferente como esta (hay más métodos en la clase, pero no afectan el guardado de archivos):

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