我有一個使用靜態方法從其他類NullPointerException異常情況下的靜態方法
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中。我認爲上下文有問題,但不知道爲什麼。
'FileRead.getContext()'返回null – donfuxx