Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the android Path string to a file on Assets folder?

I need to know the string path to a file on assets folder, because I'm using a map API that needs to receive a string path, and my maps must be stored on assets folder

This is the code i'm trying:

    MapView mapView = new MapView(this);     mapView.setClickable(true);     mapView.setBuiltInZoomControls(true);     mapView.setMapFile("file:///android_asset/m1.map");     setContentView(mapView); 

Something is going wrong with "file:///android_asset/m1.map" because the map is not being loaded.

Which is the correct string path file to the file m1.map stored on my assets folder?

Thanks

EDIT for Dimitru: This code doesn't works, it fails on is.read(buffer); with IOException

        try {             InputStream is = getAssets().open("m1.map");             int size = is.available();             byte[] buffer = new byte[size];             is.read(buffer);             is.close();             text = new String(buffer);         } catch (IOException e) {throw new RuntimeException(e);} 
like image 882
NullPointerException Avatar asked Dec 12 '11 13:12

NullPointerException


People also ask

How do I access assets files on Android?

Step 3 – Right click app >> New >> Folder >> Assets folder. Right click on the assets folder, select New >> file (myText. txt) and your text.

How do I get to my assets folder?

File > New > folder > assets Folder Two ways: Select app/main folder, Right click and select New => Folder => Asset Folder.


1 Answers

AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.

So, you really can't make stuff that expects a file accept an asset 'file'.

Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:

  File f = new File(getCacheDir()+"/m1.map");   if (!f.exists()) try {      InputStream is = getAssets().open("m1.map");     int size = is.available();     byte[] buffer = new byte[size];     is.read(buffer);     is.close();       FileOutputStream fos = new FileOutputStream(f);     fos.write(buffer);     fos.close();   } catch (Exception e) { throw new RuntimeException(e); }    mapView.setMapFile(f.getPath()); 
like image 61
Jacob Nordfalk Avatar answered Sep 18 '22 12:09

Jacob Nordfalk