Android - Problema al crear archivo en SD

 
Vista:
Imágen de perfil de jose

Problema al crear archivo en SD

Publicado por jose (2 intervenciones) el 29/05/2022 12:39:30
Buenas tardes a todos,

Tengo la intención de crear un pequeño programa que almacene en un archivo que almacene datos
desde un formulario.

Tipo :

1
2
insert into movimientos ('titulo','entidad','cantidad','fecha','operacion','descripcion') values
('compra','Supermercado',10.0,'15/05/2022','gasto','bla bla bla'),

El problema que tengo que es que no crea el archivo, al debuggear sale el siguiente error:

java.io.FileNotFoundException: /storage/emulated/0/OfflineGestion/control.txt (No such file or directory)

Expongo todo el método onCreate donde compruebo si el archivo existe (funciona)

El problema lo tengo con el método crearArchivo(f_archivo); donde en la línea que corresponde al código


fr = new FileWriter(fileSt); salta directamente a la excepcion
1
2
3
4
5
} catch (IOException e) {
            Toast.makeText(this,"No se pudo guardar",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
 
Lo he probado en eclipse y funciona perfectamente, pero no con android studio y con el emulador del propio IDE.


Expongo las variables globales y el método OnCreate, más abajo el método crearArchivo() donde falla.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private String nombreArchivo = "control.txt";
private String nombreCarpeta = "OfflineGestion";
 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);
 
        File tarjeta_sd = Environment.getExternalStorageDirectory();
        f_carpeta = new File(tarjeta_sd.getAbsolutePath(),nombreCarpeta);
        //f = new File()
        if (!f_carpeta.exists()) {
            f_carpeta.mkdirs();
        }
 
        String pathArchivo = Environment.getExternalStorageDirectory() + File.separator + nombreCarpeta + File.separator + nombreArchivo;
        //Si el archivo no existe, crear archivo con contenido básico
 
 
        f_archivo = new File(pathArchivo);
        if (!f_archivo.exists()) {
            crearArchivo(f_archivo);
        }
 
        sptitulo = (Spinner) findViewById(R.id.sptitulo);
        //Creating the ArrayAdapter instance having the list
        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,tituloSpinner);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //Setting the ArrayAdapter data on the Spinner
        sptitulo.setAdapter(aa);
 
 
        edEntidad = (EditText) findViewById(R.id.entidad);
        edCantidad = findViewById(R.id.cantidad);
        initDatePicker();
        dateButton = findViewById(R.id.fecha);
        dateButton.setText(getTodayDate());
        edDescripcion = findViewById(R.id.edDescripcion);
 
        rbGasto = findViewById(R.id.rbGasto);
        rbIngreso = findViewById(R.id.rbIngreso);
        chExtra = findViewById(R.id.chExtra);
        chExtraEspecial = findViewById(R.id.chExtraEspecial);
 
 
    }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private void crearArchivo(File f) {
 
        FileWriter fr = null;
        PrintWriter pw = null;
        String fileSt = f.toString();
        try {
 
            fr = new FileWriter(fileSt);
            pw = new PrintWriter(fr);
 
            pw.println("insert into movimientos ('titulo','entidad','cantidad','fecha','operacion','descripcion') values");
 
 
            //fr.flush();
 
            Toast.makeText(this,"Guardado correctamente",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(this,"No se pudo guardar",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } finally {
             try {
                 if (null != fr) {
                     fr.close();
                 }
             } catch (Exception e2) {
                e2.printStackTrace();
             }
 
        }
    }
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de jose

Problema al crear archivo en SD

Publicado por jose (2 intervenciones) el 29/05/2022 22:10:37
Al que se me olvidó comentar

En el AndroidManifest.xml tengo los siguientes permisos

1
2
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Y en el Activity principal el requerimiento de los permisos

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int permissionCheck = ContextCompat.checkSelfPermission(
                this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            Log.i("Mensaje", "No se tiene permiso para realizar ESCRIBIR EN SD.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
        } else {
            Log.i("Mensaje", "Se tiene permiso!");
        }
 
        permissionCheck = ContextCompat.checkSelfPermission(
                this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            Log.i("Mensaje", "No se tiene permiso para realizar ESCRIBIR EN SD.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 225);
        } else {
            Log.i("Mensaje", "Se tiene permiso!");
        }

Al iniciar me pregunta si permitir o denedar, pero luego no crea nada en el SD.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

go to this site

Publicado por samlow1997 (1 intervención) el 12/07/2022 16:34:49
Are you not one of those who are used to working for days on a course project, forgetting about your own personal life? Or just can't, for an objective reason, write a term paper yourself? There is only one way out - to order a ready-made term paper from specialists https://essaywriter.org/buy-personal-statement-online and make sure that it is very simple and inexpensive. The quality of the work performed will be beyond praise! See for yourself
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar