Rafael Lima
Rafael Lima

Reputation: 3535

Android can't open file in assets folder

My app allows user to export its data to other users or just to save as backup.
The import/export is working FINE

In order to let the user have a sample data when it first installs my app I want to package some default data. I created the sample data, tested IS WORKING FINE, then i packaged it in assets folder and load it when user runs the app for first time.

But i'm getting file not found exception

HERE GOES THE CODE:

  private List<Giveaway> loadJsonData(Uri data, User user) {
        List<Giveaway> result = null;
        try {
            InputStream is = this.getContentResolver().openInputStream(data);
            Gson parser = new GsonBuilder().setDateFormat("dd/MM/yy").setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setLongSerializationPolicy(LongSerializationPolicy.DEFAULT).setLenient().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.TRANSIENT).create();

            Set<Giveaway> temp = new HashSet<Giveaway>(50);
            temp.addAll((Collection<? extends Giveaway>) parser.fromJson(new InputStreamReader(is), TypeToken.getParameterized(List.class, Giveaway.class).getType()));



            result = new ArrayList<Giveaway>(temp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result = new ArrayList<Giveaway>(1);
        }

        return result;


    }

and I call it using:

loadJsonData(Uri.parse("file:///android_asset/giveaway_export.json"), sampleUser);

Upvotes: 1

Views: 3622

Answers (2)

Jorgesys
Jorgesys

Reputation: 126445

Use AssetManager this is an example:

 AssetManager assetManager = getAssets();
            InputStream is = null;
            try {
                is = assetManager.open("giveaway_export.json");
            } catch (IOException e) {
                e.printStackTrace();
            }

so you have to change your method:

 private List<Giveaway> loadJsonData(Uri data, User user) {
        List<Giveaway> result = null;
        try {
            //InputStream is = this.getContentResolver().openInputStream(data);
            AssetManager assetManager = getAssets();
            InputStream is = null;
            try {
                is = assetManager.open("giveaway_export.json");
            } catch (IOException e) {
                e.printStackTrace();
            }
            Gson parser = new GsonBuilder().setDateFormat("dd/MM/yy").setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setLongSerializationPolicy(LongSerializationPolicy.DEFAULT).setLenient().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.TRANSIENT).create();

            Set<Giveaway> temp = new HashSet<Giveaway>(50);
            temp.addAll((Collection<? extends Giveaway>) parser.fromJson(new InputStreamReader(is), TypeToken.getParameterized(List.class, Giveaway.class).getType()));



            result = new ArrayList<Giveaway>(temp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result = new ArrayList<Giveaway>(1);
        }

        return result;

    }

Remember if you are using android 6.0+ you need to declared the permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

and require manually permissions:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    //Verify permission for Android 6.0+
     checkExternalStoragePermission();
}

use this method:

private void checkExternalStoragePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        Log.i("Message", "You require permissions!.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
    } else {
        Log.i("Message", "you have already permissions!");
    }
}

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006604

file:///android_asset works for WebView and pretty much nothing else. Use AssetManager to work with assets — you get one of these by calling getAssets() on a Context, such as your Activity.

Upvotes: 1

Related Questions