简体   繁体   English

将数据传递到另一个活动

[英]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'? 红色强调了“数据”,因此我很确定“数据”有问题吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM