Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在TextView.setText()中获取applicationContext_Android_Nullpointerexception_Textview_Subclass - Fatal编程技术网

Android 在TextView.setText()中获取applicationContext

Android 在TextView.setText()中获取applicationContext,android,nullpointerexception,textview,subclass,Android,Nullpointerexception,Textview,Subclass,我正在构建一个TextView子类来更改插入到android:text中的文本。例如,我想将整个文本大写,但为了确保需要,我需要访问应用程序实例(我有一个布尔值,告诉它是否必须大写) 我实现了这个子类: public class UpperTextView extends TextView { private Context context; public UpperTextView(Context context) { super(context); this.contex

我正在构建一个
TextView
子类来更改插入到
android:text
中的文本。例如,我想将整个文本大写,但为了确保需要,我需要访问应用程序实例(我有一个布尔值,告诉它是否必须大写)

我实现了这个子类:

public class UpperTextView extends TextView {

private Context context;

public UpperTextView(Context context) {
    super(context);
    this.context = context;
}

public UpperTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
}

public UpperTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
}

@Override
public void setText(CharSequence text, BufferType type) {
    //I get a NullPointerException here since var context is null
    Context applicationContext = context.getApplicationContext();

    if (text != null && applicationContext instanceof MyApplication && applicationContext.doUppercase()) {

        MyApplication myApp = (MyApplication) applicationContext;
        myApp.getLanguagesController().getLocalizedString(text.toString().toUpperCase());
    }
    super.setText(text, type);
}
}
在布局中,我这样声明它

            <my.package.UpperTextView
            android:id="@+id/foo"
            android:text="bar"/>

调用
context.getApplicationContext()
时,我得到一个NullPointerException


是否有人遇到过此问题?

查看下面的链接,了解何时使用getApplicationContext()以及何时使用活动上下文


大多数情况下,最好使用活动上下文

这是不正确的本地化方法。查看以下链接:
我想你应该试试这个:

this.getContext().getApplicationContext()

这不应返回空指针异常

您不需要跟踪上下文,您可以在ViewThing中调用getContext,事务由服务器提供。。。因此,我无法将资源文件夹用于它