Android static vs nonstatic issue
I've been trying to call the following:
public static void startfile() {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get an error that tells me that "Cannot make a static reference to the non-static method openFileOutput(String, int) from the type ContextWrapper"
So I searched for that error and found this site.
I implemented this:
public static void startfile(Trackfile O) {
Log.i("File Works", "working2 ");
O.nonstatstartfile();
}
public void nonstatstartfile(){
Log.i("File Works", "nonStat");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I call startfile from another 开发者_开发问答class getting a Null pointer error. What argument do I need to send to avoid the null pointer error?
You can pass context
from activity like below
public static void startfile(Context c) {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = c.openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void startfile() {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add this method to your class, and use it without problems. If you need it in main class, use it over object.
精彩评论