简体   繁体   中英

How to solve error about saving Android Kotlin file

How to solve it? I created a program that periodically creates and stores cell phone sensor data in a file in the cell phone Download folder. It works fine the first time you run it, but if you want to create a new file again, delete the file in the path folder and run it again, an EExit error occurs. In the way that the file already exists in /storage/emulator/0/~~ path. What should I do to fix this error? The code to write the file is as follows.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setChart()
        checkFunction()

        val saveButton: Button = findViewById(R.id.btn_save)
        saveButton.setOnClickListener{
            if(isSaving){
                // Stop saving data
                isSaving = false
                saveButton.text = "Save Start"
                // Display a toast message to confirm that the data was saved
                Toast.makeText(this, "Stop Sensor data saved to file", Toast.LENGTH_SHORT).show()
            } else {
                // Start saving data
                isSaving = true
                saveButton.text = "Save Stop"

                // Check if app has permission to write to external storage
                if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
                    //Request permission if it doesn't already have it
                    ActivityCompat.requestPermissions(this, permission_list, 1)
                } else {
                    // Display a toast message to confirm that the data was saved
                    Toast.makeText(this, "Start Sensor data saved to file", Toast.LENGTH_SHORT).show()
                    // Define file
                    saveCounter++
                    // if permission is already granted, start saving sensor data in a background thread
                    GlobalScope.launch(Dispatchers.IO) {
                        while(isSaving){
                            saveSensorDataToFile()
                            delay(1000)
                        }
                    }

                }
            }
        }
    }

// -------------------- Save Data at File -------------------

    private fun saveSensorDataToFile() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            // Get the path to the exteranl storage
            val root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            val dir = File(root.path + "/SensorData3")
            dir?.mkdirs()
            val fileName = "Sensor_data_$saveCounter.txt"
            val file = File(dir, fileName)
            val sdf = SimpleDateFormat("MM-dd HH:mm:ss", Locale.getDefault())
            val currentDate = sdf.format(Date())
            val data = "$currentDate, $pre_x, $acc_x, $acc_y, $acc_z\n"
            file.appendText(data)
        } else {
            // Permission not granted, request permission
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                0
            )
        }
    }

    // 권한 확인 함수
    private fun checkFunction() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(this, arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE), 101)
            } else {
                ActivityCompat.requestPermissions(this, arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE), 101)
            }
        }
    }


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="10"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_acc"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="acc_value"
                android:textSize="20dp"
                android:textAlignment="center"
                android:gravity="center"/>

            <TextView
                android:id="@+id/tv_pressure"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="pressure_value"
                android:textSize="20dp"
                android:textAlignment="center"
                android:gravity="center"/>

        </LinearLayout>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:orientation="horizontal">

            <com.github.mikephil.charting.charts.LineChart
                android:id="@+id/chart_accX"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="2"/>

            <com.github.mikephil.charting.charts.LineChart
                android:id="@+id/chart_accY"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="2"/>

            <com.github.mikephil.charting.charts.LineChart
                android:id="@+id/chart_accZ"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="2"/>

        </LinearLayout>

        <com.github.mikephil.charting.charts.LineChart
            android:id="@+id/chart_pressure"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"/>

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/btn_save"
        android:text="Save Start"
        android:textSize="20dp"/>

</LinearLayout>
val file = File(dir, fileName)
var fileExists = file.exists()

if(fileExists){
   // file already there. so delete and new here
} else {
   // create new file
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM