Search code examples
androidandroid-activity

Android Studio an array in onStop()


why does the program crash at "String temp_str = string_array[1]" ? Logcat: java.lang.NullPointerException: Attempt to read from null array.

public class MainActivity extends AppCompatActivity {
public String string_array[];

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

    String string_array[]=new String[10];

    string_array[1]="word1";
    string_array[2]="word2";
    string_array[3]="word3";


}


@Override
protected void onStop(){
    super.onStop();

    String temp_str = string_array[1];

}

}


Solution

  • Delete this line in onCreate():

    String string_array[]=new String[10];
    

    In class scope use this declaration:

    public String[] string_array = new String[10];
    

    And delete this one:

    public String string_array[];