我想知道如何傳遞和讀取來自另一活動的一個活動的字符串。我有兩個活動。我會稱它們爲Activity1和Activity2。我在Activity1中有一個名爲course
的字符串。我想在Activity2中讀取該字符串。如何將字符串從一個活動傳遞到另一個活動?
我試過這樣做,但字符串出來空。
public class Activity2 extends Activity1 {
我見過的人使用意向的功能,但我無法弄清楚如何使用它。
有什麼建議嗎?謝謝!
我想知道如何傳遞和讀取來自另一活動的一個活動的字符串。我有兩個活動。我會稱它們爲Activity1和Activity2。我在Activity1中有一個名爲course
的字符串。我想在Activity2中讀取該字符串。如何將字符串從一個活動傳遞到另一個活動?
我試過這樣做,但字符串出來空。
public class Activity2 extends Activity1 {
我見過的人使用意向的功能,但我無法弄清楚如何使用它。
有什麼建議嗎?謝謝!
使用意圖傳遞值。
在您的第一項活動
Intent i= new Intent("com.example.secondActivity");
i.putExtra("key",mystring);
// for explicit intents
// Intent i= new Intent(ActivityName.this,SecondActivity.class);
// parameter 1 is the key
// parameter 2 is the value
// your value
startActivity(i);
在你的第二個活動進行檢索。
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//get the value based on the key
}
要自行傳遞對象,你可以在此鏈接
http://www.technotalkative.com/android-send-object-from-one-activity-to-another-activity/
謝謝!有效。 – 79t97g 2013-04-07 06:19:14
@ezcats接受答案,如果有幫助。 – Raghunandan 2013-04-07 06:21:41
我只能在10分鐘後接受它。我已經做了。 – 79t97g 2013-04-07 06:32:10
你在正確的軌道上 - 你正在使用的意圖,啓動第二個活動。您只需添加intent.putExtra("title", stringObject);
其中stringObject是要傳遞的字符串,而title是要爲該對象提供的名稱。您使用該名稱來引用在第二個活動中傳遞的對象,如下所示:
String s = (String)getIntent().getExtras().getSerializable("title");
您的第一項活動,看看Activity1
public class Activity1 extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
btn=(Button) findViewById(R.id.payBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent(Activity1.this,Activity2.class);
intent.putExtra("course", "courseValue");
startActivity(intent);
}
});
}
}
Activity2
public class Activity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String course=getIntent().getExtras().getString("course").toString();
Log.d("course",course);
}
}
希望這會幫助你。
從活動一呼是這樣的:
Intent intent= new Intent("path.secondActivity");
intent.putExtra("keyString",sampleString);
startActiivty(intent);
,並在活動2嘗試這樣:
Bundle values = getIntent().getExtras();
if (values != null) {
String keyString = values.getString("keyString");
}
在您的MainActivity
Intent i= new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("key",yourstring);
startActiivty(i);
在你的第二個活動的onCreate ()
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
}
你能粘貼完整的代碼嗎?如果課程是Activity1的一部分,請嘗試使用Activity2擴展Activity1。 – 2013-04-07 06:08:15
我改正了它。我打算在輸入問題時寫下。它不會給出任何錯誤,它只是空的。 – 79t97g 2013-04-07 06:10:10
使用'意圖'是正確的方法。 – Swayam 2013-04-07 06:13:27