newman
newman

Reputation: 163

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];

}

}

Upvotes: 2

Views: 84

Answers (3)

otto
otto

Reputation: 190

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[];

Upvotes: 2

Panicum
Panicum

Reputation: 824

Program crash because you are declaring localy (in onCreate()) second variable with name string_array[] and you initialize only this one variable. Your global variable public String string_array[] isn't initialized anywhere so is null. To make this code working you should delete declaration in onCreate() and move initialization to global variable declaration:

public class MainActivity extends AppCompatActivity {
public String string_array[] = new String[10];

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

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


}


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

    String temp_str = string_array[1];

   }
}

Upvotes: 2

touhid udoy
touhid udoy

Reputation: 4442

You have defined String string_array[] twice. Once in class scope and once in onCreate() method.

For intended behavior, delete the declaration inside onCreate()

For example, delete this line inside onCreate()

String string_array[]=new String[10];

Upvotes: 3

Related Questions