Let's say we call a method on a variable fetched through findViewById():
TextView tv = (TextView) findViewById(R.id.text);
tv.setText("Some text");
Android Studio automatically warns us that setText() may produce a NullPointerException if tv turns out to be null. If we however are certain that tv will never be null (unless something really wonky happens which should crash the app anyway), is it really worth encapsulating the method call within an if(tv != null){} statement? What if these two (or more) rows are executed very often? Can we gain any significant performance increase?
I personally don't think there is much point in checking these are null because you will know if they are present in your layout file or not, so I wouldn't bother.
However, I do sometimes use the following to prevent the warnings in Android Studio:
assert tv != null;
I don't know how this affects performance but I imagine it will have almost no difference.
Throwing or creating new exceptions will definitely consume more resources than what you might expect BUT it is always good to handle the exception where necessary rather than let the app crash. IF you are absolutely certain that the textview or whatever UI element ISpresent in the correct XML for your activity and/or the fragment then i don't think that you should use try catches at all..
Yes you can use asserts to avoid warning of Android Studio as mentioned above, and with respect to performance I don't think you will notice any huge performance variation. However, its always good to catch exceptions and log them as it can be really useful while debugging.
Actually, it can be null.
If you have complicated layout, and many ids, it can happen if you type id of other layouts.
This is only a warning. If your layout is simple to remember all ids or you sure it's never null, don't bother this warning.
This warning is helpful when you change an id in layout manually.
EX:
layout 1 has ids : text_view_1, button_1
layout 2 has ids : text_view_1, button_2
Activity 2 use layout 2 and findViewById(text_view_1)
If you change from text_view_1 to text_view_2 (MANUALLY by typing). No error happened, because id text_view_1 is still exits. But NullPointerException will occur when you run application.
Related
So, I have this android application and even some users. As I have a crash report system, I can see when someone's app crashes and the cause.
It appears that, though rarely, the app crashes randomly with NullPointerException when it tries to change some attributes(rotation, text, etc..). I make sure everything is set first thing in the onViewCreated method(using Fragments) like this:
private TextView orientationView;
orientationView = this.getActivity().findViewById(R.id.orientationView);
Using this ^^ example, I then try to hide/show this view and get an exception as it appears to be null sometimes, which is what I struggle to figure out why.
orientationView.setVisibility(View.VISIBLE); // app crashes when orientationView is null
Being a newbie in android development, I am not sure if it is a good practice, but in some of the fragments, I set all the previously initialized resources to null in the onDestroyView method, but the one that crashes the most doesn't have this method implemented, which make me to believe that somehow the resources are just not found/initialized in some rare occasions and I fail to change them later with an exception.
Could someone help me figure this out :) (more description could be provided, if needed)
I'm writing an Android program I put a ImageView on screen and then remove it but another part of the code is still trying to detect the ImageView after it has been removed. How do I write an if statement that will allow me to detect if the imageView has been removed? I've tried a few things but get no result
if (arrowObj000.get(6).findViewWithTag(arrowObj000.get(6))!=null) {
}
arrowObj00 is a list object/array holding refrences to the ImageView this isn't the problem though
Problem is I need to write an if statement that detects if the ImageView is currently attached.
Walk up the chain of parents, comparing each to the root view of the activity/fragment. If you hit the root, you're attached. If you find a null first, you aren't.
Although a better way to handle this would probably to store the state information somewhere and not use your view as state.
After thoroughly looking through the code hints I found the answer
if (arrowObj000.get(6).isAttachedToWindow()) {
}
To get better programming skills, I read some sources from others.
I ask myself everytime, what the best way of validation is.
Here you will find some seafile code snippets for android. I'm wondering, why nobody will check in line 109, if ActionBar is null.
On other posts here on SO, I found something like this:
TextView Foo = (TextView) findViewById(R.id.FooBar)
In that post it was said, that this can result in a NullPointer or CastException. That's right. Unfortunately, even Google doesn't do this validation in its own reference.
Do you have any idea, how to deal with it? When should I check, if something is Null or not?
In my opinion
TextView Foo = (TextView) findViewById(R.id.FooBar)
is an example in which it's either always null or never null or CastException or no exception. So I'd not check it for null or check for that exception, since it never changes. If it runs once, it will always run ;)
I'd rather concentrate on checking for null whenever the result actually can be null or not null.
until now I couldn't find any answer that suits my problem/question.
In android studio it often shows a notice that e.g. findViewById may produce a NPE, althogh i know the item IS existing in the layout I use.
I also never got a NPE thrown at this locations at runtime, so why the warning/notice?
I just don't know how I have to react/handle to such warnings/infos in the code view? Are there any tips to avoid that messages (because for me it looks like valid and working code)? It's only the warnings in the code view, that makes me uncertain.
Here a snippet where a warning is shown on findViewByID.
//fetch predefined item layout
row = inflater.inflate(R.layout.view_searchresult_item,null);
//get table layout for inserting items
TableLayout itemtablelayout = (TableLayout)row.findViewById(R.id.resultitem_tablelayout);
Warning is not an Error. And the warning which you are talking about says "it may produce", don't say 'it must produce'. So choice is yours. Either add null check or not
So, If you are sure that findViewById in your code will never be cause of NPE, then don't add the null check.
I need help with using an if statement in java, here is my code :
if(ans==1)
{
txtans.setText("This is a Prime Number");
}
else
{
txtans.setText("This is NOT a Prime Number");
}
if I remove the setText methods in both statements my program works, but when I leave them there and the program finds ans, then it quits, I'm wondering whats wrong with the statements? or is it not possible to use the setText method within if statements..if so how do I overcome this? What I want to do is print a string to the TextView layout when the ans = 1, any suggestions?
Yes, you can run txtans.setText() in an if statement just as well as you could run it if it wasn't in an if statement. You likely just don't have txtans initialised properly.
A quick google search brought up this as a way to print text to a textview.
Check your code, this erros usually comes when use findViewById() method in a wrong view.
In the activity you use like this findViewById(), maybe you need to call yourView.findViewById();
(If you post your class we can help you with more detailed answear.)
Also note that it is not allowed to call methods from Views from another Thread which created them. But a LogCat output including the Error will enlight us for shure :)
txtans might be NULL and you are trying to access a member of a NULL object.