Nullpointerexception thrown when trying to findViewById

别说谁变了你拦得住时间么 提交于 2019-11-28 02:24:44

Write code to initialize button from fragment becuase your button is into fragment layout not into activity's layout.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_main, container,
            false);
    Button login = (Button) rootView.findViewById(R.id.loginButton);
    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(MainActivity.this,
                    LoginActivity.class);
            startActivity(intent);
        }
    });

    return rootView;
}

And remove the login button related code from onCreate of Activity.

Try to implement your onCreateView(...) in Fragment like

@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
 View rootView = inflater.inflate(R.layout.fragment_main, container,
  false);

 View something = rootView.findViewById(R.id.something);
 something.setOnClickListener(new View.OnClickListener() { ... });

return rootView;
}

The Button is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.

findViewById() works with reference to a root view. Without having a view in the first place will throw a null pointer exception

In any activity you set a view by calling setContentView(someView);. Thus when you call findViewById() , its with reference to the someView. Also findViewById() finds the id only if its in that someView. So in you case null pointer exception

For fragments, adapters, activity, .... any view's findViewById() will only find if the id exixts in the view Alternately if you are inflating a view, then you can also use inflatedView.findViewById() to get a view from that inflatedView

In short make sure you have the id in your layout you are referring to or make findViewById() call in appropriate place(Ex. adapters getView(), activity's onCreate() or onResume() or onPause() , fragments onCreateView(), ....)

Also have an idea about UI & background thread's as you cannot efficiently update UI in bg-threads

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