java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference

后端 未结 3 1942
暗喜
暗喜 2020-12-30 07:51

I always get an Error in my Android Project.

java.lang.NullPointerException: Attempt to invoke virtual method \'android.view.View android.app.Activi

相关标签:
3条回答
  • 2020-12-30 08:19

    It's very simple

    public class MainActivity extends AppCompatActivity {
    
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button btn1 = (Button) findViewById(R.id.button1);
    
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  Intent intent = new Intent(MainActivity.this, YourNextClass.class);
                    startActivity(intent);
                }
            });
    
        }
    }
    
    0 讨论(0)
  • 2020-12-30 08:38

    In addition to what @Selvin pointed out, it looks like this:

    Button add = (Button) activity.findViewById(R.id.add);
    

    ...should be changed to this:

    Button add = (Button) rootView.findViewById(R.id.add);
    
    0 讨论(0)
  • 2020-12-30 08:40

    Use the following code:

     listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
           //     selectedPosition = position;
    
                View newTypeView=listView1.getChildAt(position-listView1.getFirstVisiblePosition()).findViewById(R.id.RelativeLayout);
    
                if (newTypeView.getClass().getName().toString().contains("RelativeLayout")) {
    
    
                    if (lastTouchedVw != null)
                        lastTouchedVw.setBackgroundColor(Color.parseColor("#ffffff"));
                     // mainImageView.setImageURI(Uri.parse(al.get(position).toString()));
                    //bigImageRelativeLayoutVw.setBackgroundColor(Color.parseColor("#ffb000"));
                        newTypeView.setBackgroundResource(R.drawable.cellbg);
    
                        lastTouchedVw = newTypeView;
                }
    
    0 讨论(0)
提交回复
热议问题