2013-02-24 43 views
0

我需要幫助才能將字符串發送到其他活動。如何在Intents之間發送字符串?

public class MainActivity extends Activity implements OnClickListener{ 

@Override 
public void onClick(View arg0) { 
    // TODO Auto-generated method stub 
    Intent myInt = new Intent(this,Receiver.class); 
    myInt.putExtra("key",Event); 
    startActivity(myInt); 
} 

Button b; 
EditText Edt; 
String Event; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     b=(Button)findViewById(R.id.button); 
     b.setOnClickListener(this); 
     Edt=(EditText)findViewById(R.id.EdtText); 
     Event=new String(Edt.getText().toString());    
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 
} 

這就是我要發送到這個活動與字符串事件的意圖

public class Receiver extends Activity { 

TextView txtV; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.receiving); 
    txtV=(TextView)findViewById(R.id.txtV); 
    Bundle extras = getIntent().getExtras(); 
    if(extras !=null) { 
     String value = extras.getString("key"); 
    } 
    txtV.setText("key"); 
} 
} 

當我運行我的程序只顯示我的「鑰匙」,但我想顯示字符串事件,儘管我在第一個意圖中使用了putExtra方法,但我無法在此活動中使用。 請幫助我,我知道還有很多其他類似的問題,但我仍然沒有得到它。

+0

你在說什麼事件? – 2013-02-24 15:41:51

+3

使用'txtV.setText(value);'而不是'txtV.setText(「key」);'在if語句裏面 – 2013-02-24 15:42:54

回答

0

試試這個。我希望它能幫助你。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    b=(Button)findViewById(R.id.button); 
    b.setOnClickListener(this); 
    Edt=(EditText)findViewById(R.id.EdtText); 
    Event=new String(Edt.getText().toString()); //Remove this line 
} 

@Override 
public void onClick(View arg0) { 
    Event = Edt.getText().toString(); //Write here 
    Intent myInt = new Intent(this,Receiver.class); 
    myInt.putExtra("key",Event); 
    startActivity(myInt); 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.receiving); 
    txtV=(TextView)findViewById(R.id.txtV); 
    Bundle extras = getIntent().getExtras(); 
    if(extras !=null) { 
     String value = extras.getString("key"); //assign it. 
     txtV.setText(value); //set it to textview. 
    } 
} 
+0

謝謝你的回答,但是它沒有運行它總是顯示鍵而不是我想要的字符串 – Marques 2013-02-24 16:10:31

+0

i嘗試過,但仍然不起作用 – Marques 2013-02-24 16:19:45

+0

這是像以前一樣的問題,它只顯示我的密鑰 – Marques 2013-02-24 16:20:09

5

使用此:

txtV.setText(value); 

不是這個:

txtV.setText("key"); 
相關問題