我正在尝试创建一个读取Json Value的类。 MainActivity
类中的函数工作正常但是,如果我尝试创建一个单独的类文件,我会得到错误:non-static method getAssets() cannot be referenced as stain context
。
我怎么解决这个问题?
public class jsonClass extends AppCompatActivity {
private static Context mContext;
static String loadJSONFromAsset(String file) {
String json = null;
try {
InputStream is = getAssets().open(file); //ERROR
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;
}
static String getJsonValue(String jsonFile, String anni, String level, String getValue) {
String value = null;
JSONObject object = null;
try {
// Seleziona il file Json
object = new JSONObject(loadJSONFromAsset(jsonFile));
//Oggetto JSON per ogni anno
JSONObject getEra = object.getJSONObject(anni);
//Lista Livelli per ogni anno
JSONObject getLevel = getEra.getJSONObject(level);
//Ritorna Valore scelto per ogni Livello
value = getLevel.getString(getValue);
} catch (JSONException e) {
e.printStackTrace();
}
return value;
}
}
如果要使用有效的上下文初始化静态mContext
,则应该能够编写
InputStream is = mContext.getAssets().open(file);
您已将类loadJSONFromAsset
声明为静态类。这是创建错误,因为当您调用方法getAssets()
时,类InputStream不是静态的。查看此链接以获取更多信息
https://developer.android.com/reference/java/io/InputStream.html
正如您从链接中看到的,InputStream类实际上是public abstract class InputStream extends Object implements Closeable
。由于此类不是静态的,因此不能在静态类中使用其方法。
使用public
和没有static
声明你的方法。
public static String loadJSONFromAsset(Context mContext, String file){
InputStream is = mContext.getAssets().open(file);
}
问题是你处于静态环境中。为了摆脱它,在你的主要活动中创建你的类jsonClass的一个实例,并摆脱你jsonClass中的所有“静态”。然后在jsonClass的实例上调用getJsonValue。
在主要班级:
jasonClass jclass= new jasonClass();
jclass.getJsonValue(....);