【问题标题】:Passing data to another activity将数据传递给另一个活动
【发布时间】:2013-07-07 22:01:15
【问题描述】:

所以我试图从一个活动中传递一些数据,但我在这样做时遇到了一些困难。

这是代码:

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

我现在如何获取新活动中的数据?我试过了,但它不起作用

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

红色下划线“数据”,所以我很确定“数据”有问题?

【问题讨论】:

    标签: java android eclipse android-intent android-activity


    【解决方案1】:

    问题在于,当您开始新活动时,您正在创建一个新意图。试试这个:

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

    关于其他活动:

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

    【讨论】:

    • 感谢您的回答。我试过了,现在它在“数据”下划线并说“无法解析数据”
    • 你在哪里声明数据?
    • 我从来没有,我如何声明数据?我以前从来没有这样做过,所以很明显我遗漏了一些东西
    猜你喜欢
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多