所以我试图从另一个活动中传递一些数据,我在这方面遇到了一些困难。
这是代码:
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");
}
红色强调“数据”,所以我很确定“数据”有问题吗?
答案 0 :(得分:2)
问题是,当您开始新活动时,您正在创建新意图。试试这个:
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");
}