gpt4 book ai didi

java - 如何在非 Activity 类中使用 Activity 方法?当我尝试使用上下文时我的程序崩溃

转载 作者:行者123 更新时间:2023-11-29 23:22:28 25 4
gpt4 key购买 nike

我正在尝试在非 Activity 类中使用 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, 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): Caught a RuntimeException from the binder stub implementation. 01-03 15:55:25.932: W/Binder(632): java.lang.NullPointerException 01-03 15:55:25.932: W/Binder(632): at android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(IInputMethodWrapper.java:280) 01-03 15:55:25.932: W/Binder(632): at com.android.internal.view.IInputMethod$Stub.onTransact(IInputMethod.java:129) 01-03 15:55:25.932: W/Binder(632): at android.os.Binder.execTransact(Binder.java:404) 01-03 15:55:25.932: W/Binder(632): at dalvik.system.NativeStart.run(Native Method) 01-03 15:55:25.932: W/InputMethodManagerService(487): Got RemoteException sending setActive(false) notification to pid 2744 uid 10036 01-03 15:55:26.572: I/ActivityManager(487): Displayed com.android.dropcalendary/.MainActivity: +4s402ms

最佳答案

在非 Activity 类中使用 Activity 方法?简而言之,你不能

但肯定有办法,你可以传入你的 Activity (这通常不是一个好主意,如果你的 Activity 被破坏,它可能导致空指针或内存泄漏)。

另一种方法是,如果您需要上下文,您可以使用 ApplicationContext。

关于java - 如何在非 Activity 类中使用 Activity 方法?当我尝试使用上下文时我的程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com