It would be "cheaper" to store reference to layout element rather than findViewById every time you need it, but wouldn't it prevent garbage collection? My assumption is that in onStop state views get destroyed, at least onSaveInstanceState is called. So, reference to a UI element in activity or fragment prevents the element from being collected - right ?
Am I wrong or should I stick to findViewById or try weakreferences ?
Thanks.
My preferred way is to store the view reference in activity if it will be accessed multiple times.
Invoke findViewById everywhere makes code ugly i think.
I don't believe store the view reference will impact the gc, cause you can use Activity to access all ui element, their references are already held.
The answer is : It depends,
If you are going to be referencing the UI repeatedly, It would be cheaper to save the references. It not, then you can just use findViewById a couple of times. In most apps under normal conditions, Either way wouldn't make much noticeable difference to performance as these tasks are not very system intensive. So my final answer would be, Do whatever is most comfortable for you in your workflow since performance gains/losses are almost negligible (unless you do this a huge number of times of times).
Related
Why Is onCreate() Preferred To Do All The Main App Tasks? Why not onResume() or onStart()? Why only onCreate()? I tried to do the main tasks like binding findViewById() setting text to text views and a lot more. They all work fine. When why do we always are preferred to do that task in onCreate()?
OnCreate serves as the first entry point into your activity, so logically it makes sense to do as much of the initialization here as possible. Often times there are cases when things need to get configured with higher priority - crash reporting services, dependency injection etc. where this would get escalated to a custom application class.
according to the docs
protected void onCreate (Bundle savedInstanceState)
Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI...
so, I suppose it is fair to say that most initialization will get done inside of onCreate, which usually means that if you were to place this into a lifecycle method which could get executed repeatedly, that could be considered redundant as you'd be assigning the same values to variables repeatedly, unless that's something you actually want to do.
However, lazy initialization is also a concept to keep in mind, being able to initialize something inside of onCreate doesn't always mean that you should, it is often times better to delay initialization until you actually need the instance.
regarding
I tried to do the main tasks like binding findViewById() setting text to text views and a lot more. They all work fine.
they definitely would, findViewById can always be used and isn't limited to being inside of onCreate, in fact the result of findViewById doesn't even have to be assigned to a variable for you to be able to use it
I have an app where I use Butterknife, and recently I found a fragment where I had failed to call unbinder.unbind() in the fragment's onDestroyView(). I fixed the problem but it made me start thinking.
What kind of errors can this cause and why? I don't have a particular error right now but I would like to know what to watch out for in the future, and the website for the library doesn't specify the problems this could cause.
Imagine you have a retained fragment and you have initialized a view using #BindView.
An orientation change happens, which results in destroying activity instance, but not this fragment, because this fragment is a retained fragment, which means, that the field that you have initialized is still there (not null) and is holding a strong reference to the view of the previous activity, which results in leaking of the activity.
Although this might take for some small amount of time (because eventually you are going to perform another ButterKnife.bind() in onViewCreated(), right? But who knows, maybe you won't), still it is better to release resources as soon as you do not need them and let the GC do its job.
I've also thought about this question some time ago and other than this I couldn't come up to another scenario where unbind() would be strongly necessary.
I have heard things about how it is bad to use setContentView()
Pattern "One activity, multiple views": Advantages and disadvantages
However I was wondering, would it be unlikely that my application will cause memory leaks, if I use setContentView() once in the onResume() method of my activity?
Whenever the user opens my app, it checks to see if something has been enabled in settings. If it has been enabled then the app uses a different screen compared to the original screen.
Therefor my code looks like this:
#Override
protected void onResume() {
super.onResume();
InputMethodManager im = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
String list = im.getEnabledInputMethodList().toString();
if(Stuff is true){
setContentView(R.layout.activityscreen_enabled);
}
}
}
Would using setContentView() be unlikely to cause memory leaks and other such problems? Or is there a better solution?
I'm doing Android since few years now and I have never done that because I like to stick to the pattern which is almost always having the setContentView in the onCreate.
However, I do not believe that you would have big troubles doing that (for the memory leaks I mean).
Nevertheless, I do not see the point of doing such a thing, the pattern of the Activity (or how I understood it) is more:
I create a view in the onCreate and I update its data in the onResume and if the data are A then add/remove this view and if the data are B add/remove this other view.
To be complete, I read your (really good) link and I think you maybe misunderstood how you can apply what Commonsware is saying: you can have multiply views without having different setContentView: your view structure needs, in this case, to be really modular and you will be able to load all the subviews dynamically (or, at least, it's how my colleague and I are doing ;) ).
For your example, I would have an empty layout for the base of the activity (let's say a blue background) and then for every view I want to have (every case), I would have a dynamic layout that I load at some point in the life cycle (probably at onResume). I do not believe that what you're doing is particularly bad but I doubt that it was thought like this ^^
This link agrees with me
If you need multiple screens use a Fragment or even create a new Activity inside of messing around with the view for some reasons
It's not good to have single Activity for the whole app or it will be so long and complicated.
Your onResume() would need to handle the new views and their ids, onClickListeners... etc.
onResume() is called many times unlike onCreate() so it would be a waste of time and memory to load the views over and over.
According to android doc in activity life cycle about onPause() and onResume()
Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.
In my app I needed to call findViewbyId() from both onCreate() and from WebChromeClient.onCompletion(). To avoid findViewbyId() returning null I resorted to calling Activity.setContentView(int viewResID) before calling findViewbyId().
It works, but now I am wondering whether I may have created a "time-bomb" in my code down the road.
Are there any caveats that I need to keep in mind when doing something like this?
There is no problem in doing so. You have to reinitialize references (every findViewById needs to be called again) and it might be troublesome if you do it A LOT of times, but it is not a time bomb at all.
Is it a good practice to null references to Activity Context, when my Activity finishes? I have 3 AsyncTask's, each of them can be running in several instances simultaneously. The update the UI in onPostExecute(). Nulling all Activity Context references in onDestroy() would be quite difficult and make the code messy. What is the best thing to do?
Check WeakAsyncTask for an example from Google of an asynctask that doesn't keep references alive beyond the activity lifecycle, and BetterAsyncTask from DroidFu for an example of a way to wire AsyncTasks so they can reconnect to new activity instances (after a rotation, for example); usage example is here.
There's probably not too much harm in keeping the references to Activity around for a short operation (e.g. a single small web request or small file write), but if there's the possibility for the tasks to pile up, it could cause a problem. For example, if your app reads a 200KB XML file from a server on creation, which let's say can takes 1 minute or more over EDGE, a quick flip of the phone open/closed 3 or 4 times could lead to 4 retained Activity instances -- you can run out of memory pretty quickly in this situation, not to mention the duplicated work.
For any really long-running processes, though, you should definitely consider an IntentService instead of an AsyncTask. They're designed for longer-running processes that aren't really tied to a specific activity - like how you can send an MMS and leave the activity to go do other things, and you get a nice happy toast informing you of the completion of the task whenever it finishes.
Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself). Try using the context-application instead of a context-activity. Nulling the references is not needed when you do not need the opposite because of the memory troubles.
If the tasks will be eligible for garbage collection themselves shortly after your Activity finishes, I see no problem in keeping the references around.
If the tasks do outlive the activity for a significant amount of time, you should set all references to the Activity Context to null. See also the article Avoiding Memory Leaks.
Either way, it is good practice to use the Application Context (getApplicationContext()) instead of the Activity Context whenever you can. In this case you can't do this, because you need to post UI messages; I'm just mentioning it for completeness.
You can hold context reference using Weak reference. http://developer.android.com/reference/java/lang/ref/WeakReference.html
Weak referenced objects can be GC'd. You should just do check if you context reference is still valid every time you use it.