Android Studio - 将getAssets()引用为静态上下文

时间:2016-08-17 17:34:41

标签: java android static-methods

我正在尝试创建一个读取Json Value的类。 LANGUAGE类中的函数可以正常工作,但如果我尝试创建单独的类文件,则会收到错误:MainActivity

我该如何解决这个问题?

non-static method getAssets() cannot be referenced as stain context

4 个答案:

答案 0 :(得分:0)

如果要使用有效的上下文初始化静态mContext,则应该能够编写

       InputStream is = mContext.getAssets().open(file);

答案 1 :(得分:0)

使用public和no static声明您的方法。

public static String loadJSONFromAsset(Context mContext, String file){

        InputStream is = mContext.getAssets().open(file); 
}

答案 2 :(得分:0)

您已将类isFlag()声明为静态类。这是创建错误,因为当您调用方法loadJSONFromAsset时,类InputStream不是静态的。 查看此链接以获取更多信息

getAssets()

正如您从链接中看到的,实际上是InputStream类  https://developer.android.com/reference/java/io/InputStream.html 。由于此类不是静态的,因此不能在静态类中使用其方法。

答案 3 :(得分:0)

问题是你处于静态环境中。为了摆脱它,在你的主要活动中创建你的类jsonClass的一个实例,并摆脱你jsonClass中的所有“静态”。然后在jsonClass的实例上调用getJsonValue。

主要课程中的

jasonClass jclass= new jasonClass(); jclass.getJsonValue(....);