Android: findViewById gives me wrong pointer?

夙愿已清 提交于 2019-12-25 00:23:20

问题


In my updateGUI() function I update each TextView like so:

((TextView) findViewById(R.id.lbTrackerLat)).setText(String.valueOf(lat));
((TextView) findViewById(R.id.lbTrackerLong)).setText(String.valueOf(lng));
((TextView) findViewById(R.id.lbTrackerAlt)).setText(String.valueOf(alt));

When I call updateGUI() from the press of a button with the onclick assigned in the onCreate, the update ALLWAYS works.

I have a locationListener that's started when the user clicks another button, and on every update event I call updateGUI() there as well, which works until the screen is first rotated, after which the screen is not refreshed for some reason.

While trying to figure out why, I've added this code to the updateGUI() function:

TextView t = (TextView) findViewById(R.id.lbTrackerPostLastRefresh);
t.setText(formattedDate);
Log.d("H","EXIT  lbTrackerPostLastRefresh="+t.toString());

After rotation (onCreate is called again), when it's called from the button click, I get 44c76a78 as the pointer. When the locationListener update function calls findVIewByID, the pointer 44c1b518 is returned!!??

I get that the layout is destroyed and recreated, but why is findViewById returning old pointer values??

Spitballing: It's as if the first instance of the View starting with the initial onCreate continues merrily on (along with it's resources) even after a new View as been instantiated when the device was rotated. Perhaps the LocationListener is doing this because I haven't stopped it. But stopping and starting it every time the device is rotated seems stupid!


回答1:


I am guessing that locationListener is an anonymous inner class of an Activity, which means that it holds a reference to its parent class. So now if this locationListener is not recreated after the onCreate() call, it will reference the old Activity, and a call to findViewById() will return objects hold by that old Activity. Not only will this cause your program to perform incorrectly, but causing memory leaks as well (basically everything created by the original Activity will be retained).

If the above is not the cause, then I'll need more information regarding locationListener and how it is used in order to help.



来源:https://stackoverflow.com/questions/10151975/android-findviewbyid-gives-me-wrong-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!