我有一个类使用其他类的静态方法
public class ArticleFragment extends Fragment {
...
// use static method to get text from file
String articleString = FileRead.readRawTextFile();
article.setText(articleString);
...
}
然后我用这个方法上课
public class FileRead extends Application {
private static Context ctx;
@Override
public void onCreate() {
super.onCreate();
ctx = this;
}
public static Context getContext(){
return ctx;
}
public static String readRawTextFile()
{
InputStream inputStream = null;
StringBuilder text = new StringBuilder();
try {
//**** E R R O R ***********************
inputStream = FileRead.getContext().getResources().openRawResource(R.raw.plik);
//***************************************
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
return text.toString();
} catch (Exception e) {
Log.e("APP", "*** "+e, e);
return null;
}
}
}
我收到错误 NullPointerException。 文件在 res/raw 中。我认为上下文有问题,但不知道为什么。
最佳答案
donfuxx 是对的; FileRead.getContext()
为空。
但是我们仍然可以获得上下文!将其作为参数传递给 readRawTextFile()
。
于是变成了:
public static String readRawTextFile(Context context);
然后将 FileRead.getContext()
更改为
inputStream = context.getResources().openRawResource(R.raw.plik);
然后将您的方法调用更改为:
String articleString = FileRead.readRawTextFile(context);
将上下文替换为
- this 或 this.getContext() - 如果您在 Activity 中调用方法
- getActivity() - 如果您在 fragment 中调用它(请注意:在使用前进行 null 检查。如果 fragment 未附加到 Activity ,getActivity() 将返回 null)
- _varWithContextIn - 如果您在 setOnClickListener 中调用它,其中“this”成为您正在创建的 onClickListener。
关于android - NullPointerException 上下文静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22117272/