I am facing a problem trying to put views into an arrayList with a loop.
This works:
String textV = "chkBox1Text";
int textI = getResources().getIdentifier(textV, "id", getPackageName());
TextView test = (TextView)findViewById(textI);
test.setText("Test 01");
However this
ArrayList<TextView> friendNames = new ArrayList<TextView>();
for(int i = 0; i < 10; i++){
String textViewID = "chkBox" + i+1 + "Text";
int current = getResources().getIdentifier(textViewID, "id", getPackageName());
TextView currentTV = (TextView)findViewById(current);
friendNames.add(currentTV);
}
friendNames.get(0).setText("Test 01"); // 0 or 1
Returns a null pointer exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at ******.FriendActivity.onCreate(FriendActivity.java:56)
Am I doing something incorrectly?
It's hard to confirm, but I think your problem is that perhaps:
friendNames.add((TextView)findViewById(currentTV));
should just be:
friendNames.add(currentTV);
since currentTV
is already a TextView, which you found in the previous line.
Rookie Mistake,
String textViewID = "chkBox" + i+1 + "Text";
Should really be
String textViewID = "chkBox" + (i+1) + "Text";
Thanks to Mike M
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.