2012-09-27 14 views

回答

0

您可以輕鬆地從一個活動傳遞數據到另一個使用捆綁或意圖獲取傳遞的數據。

讓我們看看使用捆綁下面的例子:

//creating an intent to call the next activity 
Intent i = new Intent("com.example.NextActivity"); 
Bundle b = new Bundle(); 

//This is where we put the data, you can basically pass any 
//type of data, whether its string, int, array, object 
//In this example we put a string 
//The param would be a Key and Value, Key would be "Name" 
//value would be "John" 
b.putString("Name", "John"); 

//we put the bundle to the Intent 
i.putExtra(b); 

startActivity(i, 0); 

在「NextActivity」你可以用下面的代碼檢索數據:

Bundle b = getIntent().getExtra(); 
//you retrieve the data using the Key, which is "Name" in our case 
String data = b.getString("Name"); 

如何只使用意向來傳輸數據。讓我們看一下例子

Intent i = new Intent("com.example.NextActivity"); 
int highestScore = 405; 
i.putExtra("score", highestScore); 

在「NextActivity」你可以檢索數據:

int highestScore = getIntent().getIntExtra("score"); 

現在你會問我,什麼意圖和包之間的差別,他們好像 他們這樣做究竟一樣的東西。

答案是肯定的,他們都做同樣的事情。但是如果你想傳輸大量的數據,變量,大型數組,你需要使用Bundle,因爲它們有更多的方法來傳輸大量的數據(也就是說,如果你只傳遞一個或兩個變量,那麼只需要使用Intent。)

+0

我有在遊標變量檢索值,然後如何通過? – Chetan

0

你應該把值放入一個包中,並將該包傳遞給開始下一個活動的意圖。示例代碼是在回答這個問題:Passing a Bundle on startActivity()?

+0

我有光標值從數據庫檢索如何通過這個?? – Chetan

+0

通常不是一個好主意,因爲你的光標不是數據它是開放套接字上的句柄,而是考慮傳遞查詢url或者解析光標放入第一個activity中的可序列化對象並傳遞該對象 – Paul

+0

我們是否可以直接將db.query從一個intent傳遞到另一個intent並在第二個顯示結果??如果是這樣怎麼辦? – Chetan

0

綁定,你想與您所呼叫轉到下一個活動的意圖發送數據。

Intent i = new Intent(this, YourNextClass.class); 
i.putExtra("yourKey", "yourKeyValue"); 
startActivity(i); 

在YourNextClass活動,您可以通過使用

Bundle extras = getIntent().getExtras(); 
    if (extras != null) { 
    String data = extras.getString("yourKey"); 
    } 
相關問題