0

I'm building a TextView subclass to change the text that is inserted in the android:text. For instance, I want to capitalize the whole text but, to make sure that it is needed, I need to access the Application instance (I have a boolean that tells if it must or not be capitalized).

I implemented this subclass:

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);
}
}

In the layout, I have it declared like this

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

I get a NullPointerException when invoking context.getApplicationContext().

Did anyone already came across this?

Miguel Ribeiro
  • 8,057
  • 20
  • 51
  • 74
  • you don't need to keep track of the context, you can call getContext from within a View – njzk2 Apr 18 '13 at 15:23

3 Answers3

1

I think you should try this :

this.getContext().getApplicationContext()

This should not return you null pointer exception.

0

Check the link below to know when to use getApplicationContext() and when to use Activity Context

When to call activity context OR application context?

Most of the times it is better to use Activity context

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

It's incorrect way for localization. Check below link: http://developer.android.com/guide/topics/resources/localization.html

Nickolai Astashonok
  • 2,878
  • 3
  • 20
  • 23