2013-07-07 65 views
1

所以我試圖從一個活動傳遞另一個數據,這樣做有一些困難。將數據傳遞給另一個活動

這是代碼:

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

這紅色下劃線「數據」,所以我敢肯定有一些錯誤「數據」?

回答

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

謝謝您的回答。我試過這個,現在它強調'數據',並說'數據無法解析' – Guy

+0

當你試圖檢索你的列表時顯示你的代碼。 –

+0

編輯我的問題 – Guy

相關問題