【发布时间】:2019-05-29 15:54:54
【问题描述】:
我正在尝试在非活动类中使用 openFileOutput 方法。当我尝试使用 MainActivity (this) 中的上下文时,程序崩溃。
在我的课堂上使用该方法的某种形式?
private Context context;
public Events(Context context) {
this.context = context;
}
public void setEvent(int year, int month, int dayNumber, int hour, int minutes, String event, String eventParameters) {
try {
OutputStreamWriter events = new OutputStreamWriter(context.openFileOutput("events.txt", Context.MODE_PRIVATE));
} catch(IOException e) {
e.printStackTrace();
} // End of try
} // End of method - setEvent
我有一个个性化的对话框,用来调用setEvent方法。
public CellOptions(final Dialog dialog) {
final Events event = new Events(dialog.getContext());
final TextView newEvent = (TextView) dialog.findViewById(R.id.newEvent), eventView = (TextView) dialog.findViewById(R.id.eventView);
newEvent.setOnClickListener(new View.OnClickListener() {
public void onClick(View option) {
event.setEvent(2018, 0, 1, 0, 0, "New year", "Nothing");
eventView.setBackgroundColor(Color.rgb(0, 0, 8));
}
});
}
public boolean showed() {
return true;
}
同样,我已经尝试在下一个表单的 MainActivity 类中使用 setEvent。
Events event = new Events(this, the next parameters);
但它不起作用。
我已搜索过有关此问题的答案,但找不到对我有帮助的解决方案。
我找到了这个页面,但同样的问题仍然存在。
how to call method in activity form non activity class
Getting activity from context in android
using openFileOutput() in a class. (not an activity)
http://www.sgoliver.net/blog/ficheros-en-android-i-memoria-interna/
当我运行我的程序时,它在使用上下文时会崩溃。
Logcat 显示:
01-03 15:55:25.932:W/Binder(632):从活页夹存根实现中捕获了 RuntimeException。 01-03 15:55:25.932: W/Binder(632): java.lang.NullPointerException 01-03 15:55:25.932: W/Binder(632): 在 android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(IInputMethodWrapper.java:280) 01-03 15:55:25.932: W/Binder(632): 在 com.android.internal.view.IInputMethod$Stub.onTransact(IInputMethod.java:129) 01-03 15:55:25.932: W/Binder(632): 在 android.os.Binder.execTransact(Binder.java:404) 01-03 15:55:25.932:W/Binder(632):在 dalvik.system.NativeStart.run(本机方法) 01-03 15:55:25.932: W/InputMethodManagerService(487): 得到 RemoteException 向 pid 2744 uid 10036 发送 setActive(false) 通知 01-03 15:55:26.572: I/ActivityManager(487): 显示 com.android.dropcalendary/.MainActivity: +4s402ms
【问题讨论】:
-
请包含 logcat 以提供有关崩溃的更多详细信息。
-
这似乎不太可能是“从非 Activity 类调用 Activity 方法”的问题...只需查看 logcat 或将其粘贴到此处以帮助提供更详细的信息。跨度>
-
您需要 logcat 的某些特定部分还是所有 logcat 信息?
-
只要异常的堆栈跟踪就可以了。
-
我放了logcat警告,有异常显示logcat,可以吗?
标签: java android crash android-context