Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

How can I input an array and save it in an intent

this is the code that i tried to write but it doesn't work

public class MainActivity extends AppCompatActivity {

public TextView mNomi;
public Button mInvio;
public String[] array;
public Button mEnd;
public int i=0;


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

    mNomi = (TextView) findViewById(R.id.nomi);
    mInvio = (Button) findViewById(R.id.invio);
    mEnd = (Button) findViewById(R.id.fine);

    mInvio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            array[i] = mNomi.getText().toString();
            mNomi.setText("");
            i = i+1;

        }
    });

    mEnd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            salvataggio(array);
        }
    });

    }

private void salvataggio (String[] array){
    Intent intent = new Intent(this, Elenco.class);
    intent.putExtra("nomi",array);
    startActivity(intent);

}

}

When you say it doesn't work, is it giving you an error when trying to put the array in, or is it not coming back out in the other activity?

2 Answers

no error, but when i start the app after i put in same data the app crash. Maybe I need dinamic array

I kinda missed the obvious there. You do need to allocate the array and give it a size with 'array = new String[n];' With a fixed array you need to check whether you're going beyond the limit of the array. That would be ok if know there's an upper limit to how many items will be in the array. Otherwise you should probably use a ArrayList. There is a method specifically for ArrayLists of Strings, putStringArrayListExtra(), and the converse getStringArrayListExtra().