简体   繁体   中英

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.

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

I hope below code would help you out regarding context for array of views. First you will just create array but before using it you will have to create object using new keyword.

LinearLayout rootview = (LinearLayout) findViewById(R.id.rootview);

ArrayList<String> words= new ArrayList<>();     

words.add("One"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten");

    int index=0;
    while(index<words.size()){

        TextView [] textViews = new TextView[words.size()];
        textViews[index] = new TextView(this);

        textViews[index].setText(words.get(index));
        rootview.addView(textViews[index]);
        index++;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM