the Lord of the Doom
the Lord of the Doom

Reputation: 93

Read JSON file from assets

I am trying to read a JSON file from assets in fragment using getAssets(), but the IDE says "can not resolve this method (getAssets())".

Code

 public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = 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;

}

Upvotes: 0

Views: 4615

Answers (2)

kgandroid
kgandroid

Reputation: 5595

Try this:

Create a 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 get the json string call the above class as:

String str=LoaderHelper.parseFileToString(context, "levels.json");

where levels.json is the json file stored in asset folder.

Upvotes: 3

Oleg Osipenko
Oleg Osipenko

Reputation: 2430

Method getAssets() is part of Context class. So if you're not calling loadJSONFromAsset() in the class that extends Context, e.g. Activity, you need to provide reference to Context as an argument to your method and then call getAssets() on it

Upvotes: 1

Related Questions