以下是我用来读取存储在assets文件夹中的JSON文件的代码。
public class ReadJson extends Activity {
public String loadJSONFromAsset() {
String json1 = null;
try {
InputStream is = getAssets().open("jsonfile1.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json1 = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json1;
}
}
该应用程序崩溃并显示
"Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference" exception.
如何解决这个问题?
答案 0 :(得分:0)
试试这段代码:
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("jsonfile1.json")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
确保您的文件路径是否存在
答案 1 :(得分:0)
您可以尝试下面的内容。
try{
StringBuilder buf=new StringBuilder();
InputStream json = getAssets().open("jsonfile1.json");
BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8"));
String str;
while ((str=in.readLine()) != null) {
buf.append(str);
}
in.close();
} catch(Exception e){
}
确保您的jsonfile1.json
是资产文件夹的文件。
答案 2 :(得分:0)
您何时致电public class ReadJson extends Activity {
@Override
protected void onCreate(Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
loadJSONFromAsset(); // call after super.onCreate()!!!!
/// ...
}
}
?看起来你在创建Activity之前调用它。请尝试以下方法:
<!-- Auth0's lock widget library -->
<script type="text/javascript" src="https://cdn.auth0.com/js/lock-9.0.js"></script>
<!-- Angular cookie wrapper library for client cookies -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-cookies.js"></script>
<!-- Auth0's Angular SDK Library -->
<script type="text/javascript" src="https://cdn.auth0.com/w2/auth0-angular-4.js"></script>
<!-- Angular wrapper for localStorage and sessionStorage. Defaults to ng-cookies if not available -->
<script src="http://cdn.rawgit.com/auth0/angular-storage/master/dist/angular-storage.js" type="text/javascript"> </script>
<!-- Angular wrapper library for JWT-->
<script src="http://cdn.rawgit.com/auth0/angular-jwt/master/dist/angular-jwt.js" type="text/javascript"> </script>