Guy
Guy

Reputation: 6522

Passing data to another activity

So I'm trying to pass some data from one activity from another and I have some difficulties doing that.

This is the code:

private TextView createNewTextView (String text){
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    final TextView newTextView = new TextView(this);
    ArrayList<String> players = new ArrayList<String>();
    Intent zacniIgro = getIntent();

    newTextView.setLayoutParams(lparams);
    newTextView.setText(text);
    players.add(text);
    zacniIgro.putStringArrayListExtra("players", players);
    return newTextView;
}

public void zacniIgro (View v){
    Intent zacniIgro = new Intent (getApplicationContext(), Igra.class);
    startActivity(zacniIgro);
}

How do I now get the data in the new activity? I tried this but it doesn't work

ArrayList<String> players = data.getStringArrayListExtra("players");

Any ideas how else I could do this?

Retrieving list:

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

    ArrayList<String> players = data.getStringArrayListExtra("players");
}

It red underlines 'data' so I'm pretty sure there's something wrong with 'data'?

Upvotes: 1

Views: 160

Answers (1)

Alexis C.
Alexis C.

Reputation: 93892

The problem is that you're creating a new intent when you start your new activity. Try this :

ArrayList<String> players = new ArrayList<String>(); //declare it outside of the function

private TextView createNewTextView (String text){
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    final TextView newTextView = new TextView(this);

    newTextView.setLayoutParams(lparams);
    newTextView.setText(text);
    players.add(text);
    return newTextView;
}

public void zacniIgro (View v){
    Intent zacniIgro = new Intent (getApplicationContext(), Igra.class);
    zacniIgro.putStringArrayListExtra("players", players);
    startActivity(zacniIgro);
}

On the other activity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_igra);
    Intent data = getIntent();
    ArrayList<String> players = data.getStringArrayListExtra("players");
}

Upvotes: 2

Related Questions