Search code examples
javaandroidarraysandroid-activityandroid-context

Setting the context of a textview array


How do i apply a context to a textview array?

TextView[] textView = new TextView[3];

for (int cell = 0; cell < 3; cell++){
    textView[cell].setText("-");
}

Apparently, this error gets thrown:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

If this was not a textview array, adding the activity context as a parameter when calling the constructor would render the object not null, solving my issue:

for (int cell = 0; cell < 3; cell++){
    TextView textView = new TextView(context);
    textView.setText("-");
}

Where, context = getActivity().getApplicationContext()

How do i set the context parameter for the textview array? What i want is dynamic variable names for each textview so i can call the individual textviews respectively.


Solution

  • You should create object before calling method. Try this:

    TextView[] textView = new TextView[3];
    
    for (int cell = 0; cell < 3; cell++) {
        textView[cell] = new TextView(context);
        textView[cell].setText("-");
    }