-5

The following code crashes the app

public class SharedPreferencesActivity extends AppCompatActivity {

Button b1=(Button)findViewById(R.id.buttonSave); //**ERROR**

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shared_preferences);
}

Whereas the following code works fine

 public class SharedPreferencesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shared_preferences);
    Button b1=(Button)findViewById(R.id.buttonSave);//**REPLACED BUTTON DECLARATION**
}

Why is this happening?

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Gaurav Thapa
  • 89
  • 10

1 Answers1

0

If you want a reference to your button globally then you should declare it outside then initialize it in onCreate

Button b1; //declare the button variable

public class SharedPreferencesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shared_preferences);

    b1 = (Button) findViewById(R.id.buttonSave); //initialize on creation
}

You should read more into the basics of Java when learning Android

Explisam
  • 749
  • 13
  • 26
  • Button button; //declare the button variable public class SharedPreferencesActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shared_preferences); button = (Button) findViewById(R.id.buttonSave); //initialize on creation } – Александр Волошиновский May 14 '21 at 08:15