我正在尝试使方法在当前活动之外的其他类中起作用。在这种情况下,如果该方法与活动在同一个类中,但每次调用它时都会出现 NullPointerException,则有一种备份机制有时会使用 toast 并且可以完美地工作。
这些是主要活动的基本内容:
Backup bckp;
private Context context = Main.this;
bckp.copyBackup(backupdir, backupdirfile, database, context);
和被调用的方法:
public void copyBackup(final String backupdir,
final String target, final String source, final Context context) {
final File sdcard = Environment.getExternalStorageDirectory();
if (sdcard.canWrite()) {
InputStream input = null;
try {
input = new FileInputStream(source);
} catch (FileNotFoundException e) {
Toast.makeText(context, "There was an error finding the database", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
File dir = new File (backupdir);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream output = null;
try {
output = new FileOutputStream(target);
} catch (FileNotFoundException e) {
Toast.makeText(context, "There was an error creating the backup", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
byte[] buffer = new byte[1024];
int length;
try {
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (IOException e) {
Toast.makeText(context, "There was an error copying the database", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
try {
output.flush();
output.close();
input.close();
} catch (IOException e) {
Toast.makeText(context, "There was an error ending the copy", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
Toast.makeText(context, "No SD card found", Toast.LENGTH_SHORT).show();
}
}
对我来说,如果所有人都在一个班级,但如果它在一个单独的班级就不行,这对我来说毫无意义……感谢您的帮助!
编辑:
05-08 14:13:24.935: E/AndroidRuntime(636): FATAL EXCEPTION: main
05-08 14:13:24.935: E/AndroidRuntime(636): java.lang.NullPointerException
05-08 14:13:24.935: E/AndroidRuntime(636): at maturaarbeit.nicola_pfister.marks.Main$9$1.onClick(Main.java:271)
05-08 14:13:24.935: E/AndroidRuntime(636): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
05-08 14:13:24.935: E/AndroidRuntime(636): at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 14:13:24.935: E/AndroidRuntime(636): at android.os.Looper.loop(Looper.java:137)
05-08 14:13:24.935: E/AndroidRuntime(636): at android.app.ActivityThread.main(ActivityThread.java:4745)
05-08 14:13:24.935: E/AndroidRuntime(636): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 14:13:24.935: E/AndroidRuntime(636): at java.lang.reflect.Method.invoke(Method.java:511)
05-08 14:13:24.935: E/AndroidRuntime(636): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-08 14:13:24.935: E/AndroidRuntime(636): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-08 14:13:24.935: E/AndroidRuntime(636): at dalvik.system.NativeStart.main(Native Method)