Problem with external storage

0

I am making my first application and I still have some problems assimilating certain concepts. The idea is to store the data captured by the phone's accelerometer and store it in the external storage for later processing with a mathematical program. As you can see in the code, I have tried to create two methods for external and internal storage, the first of these being the one that gives me an error. Where have I missed? Where is the generated .txt supposed to be stored? Thank you very much for your help.

Here is the manifest:

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


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Here the .java:

 public class MainActivity extends Activity implements SensorEventListener{
    TextView x,y,z;
    EditText dnombre;
    private Sensor sensor;
    private SensorManager acelerometro;
    private long tiempoCreacion;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);






        acelerometro=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
        sensor=acelerometro.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        //convertimos en variables los displays de pantalla
        x=(TextView)findViewById(R.id.xID);
        y=(TextView)findViewById(R.id.yID);
        z=(TextView)findViewById(R.id.zID);
        dnombre = findViewById(R.id.nombreArchivo);




    }
     public void onResume(View vista){
        super.onResume();
        acelerometro.registerListener(this,sensor, SensorManager.SENSOR_DELAY_FASTEST);
         tiempoCreacion = System.currentTimeMillis();


     }


    public void onPause(View vista){
        super.onPause();
        acelerometro.unregisterListener(this);



    }

    // concatenamos los xmil datos que nos entran, como variable solo entran datos xq el nombre lo ponemos nosotros
   public void escribirCsv(String fileContents) {



       //introducimos el nombre del file por la interfaz
       String nombre = dnombre.getText().toString();
        FileOutputStream outputStream;

        try {
            outputStream = openFileOutput(nombre, Context.MODE_APPEND | Context.MODE_PRIVATE);
            outputStream.write(fileContents.getBytes());
            outputStream.close();

            //Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //guardar en almacenamiento externo
    public void escribirCsvEx(String fileContents) {




        String nombre = dnombre.getText().toString();
        File datos = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "datos");
        if (!datos.mkdirs()) {
            System.out.println("directorio no creado");
        }

    }


    // comprobaciones de si se puede guardar en almacenamiento externo
    private boolean isExternalStorageWritable(){
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            System.out.println("es escribible");
            return true;
        }else{
            return false;
        }
    }

    public boolean checkPermission(String permission){
        int check = ContextCompat.checkSelfPermission(this, permission);
        if(check == PackageManager.PERMISSION_GRANTED){
            System.out.println("tenemos permisos");
        }
        return (check == PackageManager.PERMISSION_GRANTED);

    }



    //guardar en almacenamiento interno
    public void writeFile(String fileContents){

        String nombre = dnombre.getText().toString();
        if(isExternalStorageWritable())// && checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
            {
            File Dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/DirectorioDatos" );
            if(!Dir.exists()){
                Dir.mkdir();
            }


                File nombre_Archivo = new File(Dir,nombre);


            try{
                FileOutputStream fos = new FileOutputStream(nombre_Archivo);
                fos.write(fileContents.getBytes());
                fos.close();

                Toast.makeText(this, "File Saved.", Toast.LENGTH_SHORT).show();
            }catch (IOException e){
                e.printStackTrace();
            }
        }else{
            Toast.makeText(this, "Cannot Write to External Storage.", Toast.LENGTH_SHORT).show();
        }
    }



    /*//crear aceleración resultante
    public void aceResult(double ax,double ay,double az){
     double ax2= pow(ax,2);
     double ay2= pow(ay,2);
     double az2= pow(az,2);
     double atot= ax2+ay2+az2;
     double aresul= sqrt(atot);
    }*/




    @Override
    public void onSensorChanged(SensorEvent event) {

        //valores a la consola
        /*System.out.println("text");
        System.out.println(System.currentTimeMillis()); //da valor en la consola no en movil*/


        long tiempo = System.currentTimeMillis()-tiempoCreacion;
        if(tiempo<=3000) {

            String tiempoString = Long.toString(tiempo);
            this.x.setText("X = " + event.values[0]);
            this.y.setText("Y = " + event.values[1]);
            this.z.setText("Z = " + event.values[2]);

            //aceleracion resultante
            double ax=event.values[0];
            double ay=event.values[1];
            double az=event.values[2];

            double ax2= pow(ax,2);
            double ay2= pow(ay,2);
            double az2= pow(az,2);
            double atot= ax2+ay2+az2;
            double aresul= sqrt(atot);






            String datos = tiempoString + ";" + event.values[0] + ";" + event.values[1] + ";" + event.values[2] + ";" + aresul + ";" + "\n";

            escribirCsvEx(datos);

            //SystemClock.sleep(7000);


        }

    }



    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
//este no vale
    }
}
    
asked by Toni Garcia Felipe 05.06.2018 в 18:36
source

0 answers