GAZZA
GAZZA

Reputation: 47

Trying to save Data to an accessible file on an android device

i have mentioned this in previous questions, I am currently using shared preferences to store some results of a BLE scan (RSSI and Time of scan) within the app. This works and the most recent scan data is accessible via an onclick button.

What i actually want is for all the scans to be stored in a file that is accessible externally from the app (Not to be confused with an external storage such as SD card). I am not using an emulator, i am using a Samsung galaxy s8 on Android 9. I have looked at some tutorials such as :

https://www.youtube.com/watch?v=ZTYR3FBDus4 (3Mins)

https://www.youtube.com/watch?v=EcfUkjlL9RI (11Mins)

And i was wondering if this "FileOutputstream onclick method" could be interpreted to store all the scanned information, for me to then access through the data file directory?

I noticed that in the first link example, showed the file to be accessible through the emulator as a .txt file. Can the same be done when using an actual android device?

EDIT: Addition of file Output stream code

                FileOutputStream fos = null;

                try {
                    fos = openFileOutput(FileName, MODE_PRIVATE);
                    fos.write(RSSI1);
                    Toast.makeText(MainActivity.this, "Saved To: " + getFilesDir() + "/" + FileName , Toast.LENGTH_LONG).show();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (fos!=null){
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

New Code:

//To create file path 
            File file = new File(Environment.getExternalStorageDirectory(), "Data");
            if (!file.mkdirs()){
                file.mkdirs();
            }
            String FilePath = file.getAbsolutePath() + File.separator + FileName;



//to print data to file in filepath
                try {
                    fileOutputStream = new FileOutputStream(FilePath);
                    fileOutputStream.write(RSSI1);

                    Toast.makeText(MainActivity.this, "Directory saved is : " + getFilesDir(), Toast.LENGTH_LONG).show();

                    fileOutputStream.close();
                }catch (FileNotFoundException e) {
                    e.printStackTrace();
                }catch (IOException e) {
                    e.printStackTrace();
                }

Upvotes: 0

Views: 105

Answers (0)

Related Questions