Matt
Matt

Reputation: 1757

Passing Array To new Activity

Ok so, I have my app which so far opens a new Activity from the SplashScreen. Once this Activity is open there is a button to add players which opens up a new Activty. In this Activty I have an Array which will be populated by a EditText box.

Once the players have been added the play button will be clicked which will got back to the previous Activity.

My question is when the play button is clicked and you go back to the previous Activty I need the Array to be carried over and populate a String.

CODE UPDATED - No force close now but the array dosent seem to be carrying over and populating strArray

I have this button to carry the Array once players have been added:

Button play = (Button) findViewById(R.id.playnow);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent( demo.AddRemove.this, demo.play.class);
Bundle extras = new Bundle();
extras.putStringArrayList( "KEY", playerList );
i.putExtras( extras );
startActivity( i );

}});
}

And this to show the Array that was carried over:

super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    if (extras == null) {
        strArray = new String[0];
    } else {
        ArrayList<String> myStrings = extras.getStringArrayList("KEY");
        if (myStrings == null) {
            strArray = new String[0];
        } else {
            strArray = (String[]) myStrings.toArray();
        }
    }

    setContentView(R.layout.passw_layout);

    initWheel(R.id.passw_1, strArray);

But as I said before When I try to open the first Activty play.java from the SplashScreen it force closes with java.lang.NullPointerException. Which I think is because the extras is empty.

Upvotes: 1

Views: 280

Answers (2)

sebastianf182
sebastianf182

Reputation: 9978

Try this:

String[] strArray;
Intent intent = getIntent();
Bundle extras = intent.getExtras();  //Added this
if (extras == null) {
    strArray = new String[0];
} else {
    ArrayList<String> myStrings = extras.getStringArrayList("KEY");
    if (myStrings == null) {
        strArray = new String[0];
    } else {
        strArray = (String[]) myStrings.toArray();
    }
}

Upvotes: 2

Brigham
Brigham

Reputation: 14524

Add a simple check for null, and create an empty array:

String[] strArray;
if (extras == null) {
    strArray = new String[0];
} else {
    ArrayList<String> myStrings = extras.getStringArrayList("KEY");
    if (myStrings == null) {
        strArray = new String[0];
    } else {
        strArray = (String[]) myStrings.toArray();
    }
}

If you don't like such a deeply nested if statement, you could also create a method to extract the array, and use early return to return the array as soon as you find a null value.

Upvotes: 1

Related Questions