1

I'm am getting a NULL pointer message on getfilesdir(). I'm sure it has something to do with my implementation but I'm not really sure what it is. Ad I'm extremely new to android development.

    public class MainActivity extends AppCompatActivity {

String appFileDirectory = getFilesDir().getPath();
String executableFilePath = appFileDirectory + "/iperf3";

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

private static final String TAG = "MainActivity";

//This function is used to copy the iperf3 executable to a directory which execute permissions for this application, and then gives it execute permissions.
//It runs on every initiation of an iperf3 test, but copies the file only if it's needed.
public void copyFile(String filename) {
    AssetManager assetManager = getAssets();
    try {
        InputStream in = assetManager.open(filename);
        File outFile = new File(appFileDirectory, filename);
        OutputStream out = new FileOutputStream(outFile);

        Log.d(TAG, "Attempting to copy this file: " + filename); // + " to: " +       assetCopyDestination);

        int read;
        byte[] buffer = new byte[4096];
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        out.close();
        in.close();

        //After the copy operation is finished we give execute permissions to iPerf3
        File execFile = new File(executableFilePath);
        execFile.setExecutable(true);

    } catch (IOException e) {
        Log.e(TAG, "Failed to copy asset file: " + filename, e);
    }
}

public static void executeIperf3() {

}
Kris Armstrong
  • 95
  • 1
  • 1
  • 7

1 Answers1

0

You try add

String appFileDirectory = getFilesDir().getPath();
String executableFilePath = appFileDirectory + "/iperf3";

into onCreate() because getFilesDir() is context method.

Tung Tran
  • 2,885
  • 2
  • 17
  • 24
  • This works if I put it in onCreate() however what would I do if I wanted the strings to be available to other methods and classes? – Kris Armstrong Mar 26 '18 at 21:00
  • You can declare `appFileDirectory` and `executableFilePath` to use for other methods but must put it inside `onCreate()` method. – Tung Tran Mar 27 '18 at 02:50
  • As @KrisArmstrong said we must use getFilesDir() in oncreate() method. And if we want to use in other classes we must use context.getFilesDir() instead. – Bhupat Bheda May 30 '18 at 05:17