Nullpointerexception thrown when trying to findViewById

前端 未结 3 1015
[愿得一人]
[愿得一人] 2020-12-07 06:15

I have the following Activity:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    supe         


        
相关标签:
3条回答
  • 2020-12-07 06:50

    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.

    0 讨论(0)
  • 2020-12-07 06:59

    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.

    0 讨论(0)
  • 2020-12-07 07:02

    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

    0 讨论(0)
提交回复
热议问题