Android/Java:如何创建静态写入方法
我目前有一个write方法来保存一些变量,我想在多个类中使用这个方法。我可以,但是我需要在那些类中的静态位置使用它,因为save方法不能是静态的 方法如下:Android/Java:如何创建静态写入方法,java,android,static,Java,Android,Static,我目前有一个write方法来保存一些变量,我想在多个类中使用这个方法。我可以,但是我需要在那些类中的静态位置使用它,因为save方法不能是静态的 方法如下: public void saveLesson(int lessons2, int problem2, int mlessons2, int mproblem2, String checkAccuracy) { String newline = System.getProperty("line.separator"); fin
public void saveLesson(int lessons2, int problem2, int mlessons2, int mproblem2, String checkAccuracy) {
String newline = System.getProperty("line.separator");
final String saved = new String(lessons + newline + problem + newline + mlessons + newline + mproblem + newline + dontCheckMaxString());
FileOutputStream fOut = null;
try {
fOut = openFileOutput("lessonStore.properties", Context.MODE_PRIVATE);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(saved);
osw.flush();
osw.close();
}
catch (IOException e) {
Toast andEggs = Toast.makeText(Lessons.this, "Error while writing...", Toast.LENGTH_SHORT);
andEggs.show();
e.printStackTrace();
}
}
所以我想我的问题是:
我如何使该方法在我所有的课程中都可用;静态方法还是非静态方法?您需要通过方法的参数创建上下文。然后可以调用Context.openFileOutput。是否也将dontCheckMaxString()设为静态?它是做什么的?抱歉,忘了将代码中的更改为方法的。无论如何,saveLesson涉及的方法不能是静态的。如果你的方法需要类的实例,如果你不能得到类的实例,你将无法使用它。我看不出你的方法在哪里需要类的实例,它从params获取一切!将Context类型的参数添加到方法中,然后对该Context对象调用openFileOutput。通过这种方式,您可以使该方法成为静态的。