1

I am attempting to capture sensor data in a textfile that I can extract from the 'external storage' of the phone when I connect it via USB to a PC so I can run the textfile through a python script for graphing purposes. I have not implemented the sensor part yet as I am unable to create files that I can copy over to the PC from the phone after they have been created.

I attempt to create a folder and it does not create the folder and I also attempt to create a file and it also fails and then it throws an exception that the file does not exist. I am at a loss as I have added the permission to the manifest file as you can see below. Is there anything that I am missing? I have done a lot of searching around and there does not seem to be any solution to my problem and the developer.android.com website does not explain anything regarding permissions outside of adding the lines I already added to the manifest file.

I do not own an SDcard so using the sdcard is not a possible solution to my problem.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mike.project_final">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_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>

    </manifest>

and here is my entire code that I have done so far which is throwing the errors.

    package com.example.mike.project_final;

    import android.content.Context;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Environment;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.hardware.Sensor;
    import android.view.View;
    import android.widget.TextView;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.PrintWriter;

    public class MainActivity extends AppCompatActivity implements SensorEventListener {



TextView xTV, yTV, zTV, writeTV;
SensorManager sManager;
Sensor sAccelerometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    xTV = (TextView) findViewById(R.id.xTV);
    yTV = (TextView) findViewById(R.id.yTV);
    zTV = (TextView) findViewById(R.id.zTV);
    writeTV = (TextView) findViewById(R.id.writeTV);
}

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

public void createFile(View view) {

    File root = android.os.Environment.getExternalStorageDirectory();
    File dir = new File (root.getAbsolutePath() + "/project_test");
    if (!dir.exists()){
        dir.mkdir();
        xTV.setText("Created");
    }
    else{
        xTV.setText("Exists");
    }
    File file = new File(dir, "myData.txt");

    try {
        FileOutputStream f = new FileOutputStream(file);
        PrintWriter pw = new PrintWriter(f);
        pw.println("Hi , How are you");
        pw.println("Hello");
        pw.flush();
        pw.close();
        f.close();
    } catch (Exception e) {
        writeTV.setText(e.toString());
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy){
    //do nothing
}
@Override
public void onSensorChanged(SensorEvent event) {

}
}

Any help with how to setup the rest of the permissions if required will be really appreciated!

EDIT 1: The issue with permissions have been solved, thank you. I now have an issue that the folder I create does not create as a folder but as a file as shown in the image below. What exactly am I doing wrong? https://i.imgur.com/srKXJc1g.png Unfortunately I don't have enough reputation to post images.

Jewgioh
  • 145
  • 10
  • https://stackoverflow.com/questions/32635704/android-permission-doesnt-work-even-if-i-have-declared-it and then https://stackoverflow.com/questions/32789157/how-to-write-files-to-external-public-storage-in-android-so-that-they-are-visibl – CommonsWare Sep 05 '17 at 19:59
  • I managed to get the permissions working but the whole thing with mediascannerconnection has my out of my element. It creates and when I try discover the folder it does not show up as a folder but instead as a blank white document of 4kB in size? Any tips you can offer in that regard? – Jewgioh Sep 05 '17 at 22:12
  • Make sure that you have fully written the file to disk before invoking `MediaScannerConnection`. See [these lines](https://github.com/commonsguy/cw-omnibus/blob/v8.7/Assist/AssistLogger/app/src/main/java/com/commonsware/android/assist/logger/AssistLoggerSession.java#L98-L109) from an otherwise unrelated book sample of mine. – CommonsWare Sep 05 '17 at 23:00
  • `dir.mkdir();`. You cry Created but you should check the return value as mkdirs() might fail. If so you should return. – greenapps Sep 05 '17 at 23:05

1 Answers1

0

My answer is kind of late but hopes it helps someone. From android 6 upwards you need to request permission from the user at runtime in your App before your App can be allowed to modify external storage. (because it is classified as a "dangerous permission". Read the documentation to learn more https://developer.android.com/guide/topics/permissions/overview#permission-groups.)

So how do you request permission.? well the code in this specific case is something like the code below (Read here https://developer.android.com/training/permissions/requesting#java to understand better) ;

 private final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 2;

 public checkWritePermissionAndCreateFile(){
 // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            // Permission has already been granted
            // Carry out functionality that you needed permission for 
             createFile();                  
        }

@Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted
                createFile();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission. 
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request.
    }

}

}
Njuacha Hubert
  • 348
  • 3
  • 13