java - Read JSON file from assets -
i trying read json file assets in fragment using getassets()
, ide says "can not resolve method (getassets())".
code
public string loadjsonfromasset() { string json = null; try { inputstream = getassets().open("moods.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new string(buffer, "utf-8"); } catch (ioexception ex) { ex.printstacktrace(); return null; } return json; }
try this:
create class loaderhelper.java
public class loaderhelper { public static string getjson(context context, string json){ string jsonstring=parsefiletostring(context, json); return jsonstring; } public static string parsefiletostring( context context, string filename ) { try { inputstream stream = context.getassets().open( filename ); int size = stream.available(); byte[] bytes = new byte[size]; stream.read(bytes); stream.close(); return new string( bytes ); } catch ( ioexception e ) { log.i("guiformdata", "ioexception: " + e.getmessage() ); } return null; } }
to json string call above class as:
string str=loaderhelper.parsefiletostring(context, "levels.json");
where levels.json json file stored in asset
folder.
Comments
Post a Comment