2 daffodilgirl DaffodilGirl 于 2013.07.08 16:12 提问

传递数据到另一个activity

需要在activity之间传递数据,遇到一些困难。

代码:

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);
}

在新的activity中如何得到数据?我试过:

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

检索列表:

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

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

给data加了红下划线。不知道是什么错误。

2个回答

abcdeFGh_xyz
abcdeFGh_xyz   2013.07.08 17:29
已采纳

因为你每次开始activity都创建了一个intent。

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);
}

在另一个activity中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_igra);
    Intent data = getIntent();
    ArrayList<String> players = data.getStringArrayListExtra("players");
}
cj6585256
cj6585256 用这个
接近 5 年之前 回复
Jave_
Jave_   2013.07.08 16:49

你的data申明在哪里??

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!