我尝试将文件拼接到类,我有文件VKFile.java:
public class VKFile extends Activity {
public VKFile() {
Log.d("BTCR", "Object VKFile created.");
}
public String read(String FILENAME){
JSONArray result = new JSONArray();
String line;
InputStream inputStream;
try {
inputStream = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
result = new JSONArray(line);
}
inputStream.close();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("BTCR", "file.read, respond: "+result);
return result.toString();
}
然后我在AuthorizedActivity.java中创建对象 - onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authorized_main);
VKFile vkFile = new VKFile();
vkFile.read("myfile");
}
运行此代码后,我的应用程序崩溃了这个日志:
java.lang.RuntimeException: Unable to start activity ComponentInfo{id.mirgorod.btcrussia/id.mirgorod.btcrussia.AuthorizedActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileInputStream android.content.Context.openFileInput(java.lang.String)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileInputStream android.content.Context.openFileInput(java.lang.String)' on a null object reference
at android.content.ContextWrapper.openFileInput(ContextWrapper.java:175)
at id.mirgorod.btcrussia.VKFile.read(VKFile.java:25)
at id.mirgorod.btcrussia.AuthorizedActivity.onCreate(AuthorizedActivity.java:129)
为什么会这样?如果我将类放在AuthorizedActivity.java中,相同的代码工作是完美的,但如果我尝试将代码放在其他类中,则给我错误。
答案 0 :(得分:0)
Toumash,谢天谢地!
除非它们是静态的,否则不要从其他Activity类调用方法,现在你要创建更多的活动 - 它们很重。而是删除扩展活动或执行
public static String read(Context context , String FILENAME){
和
inputStream = context.openFileInput(FILENAME);
然后通过
使用它VkFile.read(AuthorizedActivity.this,"myfile");