[英]How to get the context from a function of a class that extends Activity in android?
I have a class that extends Activity, When I try to access the context from the onCreate() method it gets printed but when I save it in a variable context and try to access it from the committext()
function as shown below, It prints null.我有一个扩展 Activity 的类,当我尝试从 onCreate() 方法访问上下文时,它会被打印出来,但是当我将它保存在一个变量上下文中并尝试从committext()
函数访问它时,如下所示,它会打印空值。 I also tried using "this" and getBaseContext()
directly from the committext()
function as it is a part of the same class, I get null pointer exception.我还尝试直接从committext()
函数中使用“this”和getBaseContext()
,因为它是同一类的一部分,我得到空指针异常。 Please help me figure out what is going wrong.请帮我弄清楚出了什么问题。
public class MainKeyboardActionListener extends Activity implements KeyboardView.OnKeyboardActionListener, View.OnTouchListener {
private Context context;
public static boolean active = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mode_keyboard, false);
context=getBaseContext();
System.out.println("contexxtt1"+context);
}
@Override
public void onStart() {
super.onStart();
active = true;
}
@Override
protected void onResume() {
super.onResume();
}
private static class myHandler extends Handler {
}
;
public void setInputConnection(InputConnection ic) {
}
@Override
public void onKey(int arg0, int[] arg1) {
// TODO Auto-generated method stub
}
@Override
public void onPress(int keyCode) {
}
@Override
public void onRelease(int keyCode) {
commitText(String.valueOf(keyCode));
}
private void handleException(int keyCode) {
}
private void removeHalantMode() {
}
private void commitText(String text) {
if(active==true) {
System.out.println("contexxtt"+context);
}
}
@Override
public void onText(CharSequence arg0) {
// TODO Auto-generated method stub
}
@Override
public void swipeDown() {
// TODO Auto-generated method stub
}
@Override
public void swipeLeft() {
// TODO Auto-generated method stub
}
@Override
public void swipeRight() {
// TODO Auto-generated method stub
}
@Override
public void swipeUp() {
// TODO Auto-generated method stub
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
active = false;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
使您的myHandler
类不是static
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.