Android Studio 3.1. In my Manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
MyApplication file:
public class MyApplication extends MultiDexApplication {
@Override
public void onCreate() {
super.onCreate();
init();
}
private void init() {
appContext = this;
}
public static Context getAppContext() {
return appContext;
}
}
In my FileUtil.java
:
public static String getAssetsFileContent(Context context, String assetsFileName) {
String content = "";
try {
InputStream is = context.getAssets().open(assetsFileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer, "UTF-8");
} catch (IOException e) {
Debug.e(TAG, "getAssetsFileContent: " + e.getMessage(), e);
}
return content;
}
In my custom class (not Activity)
@Override
public void onError(ErrorResponse errorResponse) {
String dictionarySetDefaultContent = FileUtil.getAssetsFileContent(MyApplication.getAppContext(), "dictionary_set_default.json");
}
In path myproject/app/src/main/res/assets
I save file dictionary_set_default.json
But I get error:
FileUtil(21086): getAssetsFileContent: dictionary_set_default.json
FileUtil(21086): java.io.FileNotFoundException: dictionary_set_default.json
FileUtil(21086): at android.content.res.AssetManager.openAsset(Native Method)
FileUtil(21086): at android.content.res.AssetManager.open(AssetManager.java:313)
FileUtil(21086): at android.content.res.AssetManager.open(AssetManager.java:287)
FileUtil(21086): at myproject.util.FileUtil.getAssetsFileContent(FileUtil.java:137)
FileUtil(21086): at myproject.service.SyncService$1.onError(SyncService.java:51)
FileUtil(21086): at myproject.api.DefaultRestClientCallback.onFailure(DefaultRestClientCallback.java:46)
FileUtil(21086): at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$2.run(ExecutorCallAdapterFactory.java:79)
FileUtil(21086): at android.os.Handler.handleCallback(Handler.java:739)
FileUtil(21086): at android.os.Handler.dispatchMessage(Handler.java:95)
FileUtil(21086): at android.os.Looper.loop(Looper.java:148)
FileUtil(21086): at android.app.ActivityThread.main(ActivityThread.java:5417)
FileUtil(21086): at java.lang.reflect.Method.invoke(Native Method)
FileUtil(21086): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
FileUtil(21086): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)