Android: open FileInputStream from apps own data directory in Java

37 views Asked by At

I'm working on an app centered around a Mapsforge map.

The map loads fine with those relevant parts from an example app, but the user has to choose the map file on each startup:

private static final int SELECT_MAP_FILE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
[..]

        Intent intent = new Intent(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ?
        Intent.ACTION_OPEN_DOCUMENT : Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(intent, SELECT_MAP_FILE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == SELECT_MAP_FILE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
            openMap(uri);
          }
       }
    }

    private void openMap(Uri uri) {
        try {
[..]
            FileInputStream fis = (FileInputStream) getContentResolver().openInputStream(uri);
            MapDataStore mapDataStore = new MapFile(fis);

Now I want to replace all that with a line or two that lets me load a map file from a known location in the apps own data directory, tried this

File mapf = new File(this.getFilesDir(), "region.map");
FileInputStream fis = new FileInputStream(File mapf);

or FileInputStream fis = this.openFileInput("region.map"); but it just doesn't work, even if it compiles.

From what I read one shouldn't need any permissions to access the apps own data, so what am I missing to get a simple, working FileInputStream?

(Currently it's all tested in the Android Studio Emulator and the region.map was placed there manually, once I can use it from there I will deal with placing the file there from assets if it doesn't exist.)

0

There are 0 answers