Kotlin Android View Binding: findViewById vs Butterknife vs Kotlin Android Extension

There are a lot of ways to access views in Android. A quick overview: My advise would be: findViewById: old school. Avoid. ButterKnife: old school, but less boilerplate and some added functionality. Still lacks compile time safety. Avoid if possible. Kotlin Synthetic: really a elegant cached version of findViewbyId. Better performance and way less boilerplate … Read more

findViewById() returns null for Views in a Dialog

Calling findViewById() will search for views within your Activity’s layout and not your dialog’s view. You need to call findViewById() on the specific View that you set as your dialog’s layout. Try this private void initSearch() { AlertDialog.Builder searchDialog = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); searchDialog.setTitle(“Search Photos”); searchDialog.setMessage(“Specify tag and value…”); // R.layout.search_dialog is … Read more

How can I assign an ID to a view programmatically?

Android id overview An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.) Assign id via XML Add an attribute of … Read more

Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?

Instance member variables are initialized when the instance itself is initialized. It’s too early for findViewById() Before onCreate() your activity does not yet have a Window that findViewById() needs internally. Before setContentView() (that you should be calling in onCreate()) there are no views to be found either. Therefore init your view references in onCreate() and … Read more

Attempt to invoke virtual method ‘android.view.Window$Callback android.view.Window.getCallback()’ on a null object reference

An Activity is not fully initialized and ready to look up views until after setContentView(…) is called in onCreate(). Only declare the fields like the following: private EditText usernameField, passwordField; private TextView error; private ProgressBar progress; and then assign the values in onCreate: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); usernameField = (EditText)findViewById(R.id.username); passwordField … Read more

Null pointer Exception – findViewById()

findViewById() returns a View if it exists in the layout you provided in setContentView(), otherwise it returns null and that’s what happening to you. Note that if you don’t setContentView(), and don’t have a valid view to findViewById() on, findViewById() will always return null until you call setContentView(). This also means variables in the top-level … Read more