2012-12-27 53 views
4

我需要從EditText上的活性的數據發送到活動B. 我想:如何將數據發送到創建活動在Android

Intent intent1=new Intent(A.this,B.class); 
intent1.putExtra("fromA", "text"); 
startActivity(intent1); 

,但它不工作,因爲活動B有android:launchMode="singleTask"和之前創建。

怎麼樣,我可以發送數據?

回答

11

您在Activity B中覆蓋onNewIntent()並在該方法中接收intent

像下面的代碼:

@Override 
protected void onNewIntent(Intent i) 
{ 
    String s = i.getStringExtra("fromA"); 
} 

在上面的代碼,你會從Activity A獲得價值s

1

你可以通過iPhone的方式做到這一點。創建一個可以在開始新活動之前設置數據並從新活動訪問相同數據的類。

這將工作如下

  1. 有兩個活動FirstActivitySecondActivity
  2. 數據要發送的姓氏和名字

所以會有一個類在這裏您將有變量的數據

public class DataTransporter{ 
     public static String firstName; 
     public static String lastName; 
} 

在第一項活動,代碼將出現

DataTransporter.firstName = "abc"; 
DataTransporter.lastName = "xyz"; 
Intent intent = new Intent(FirstActivity.this,SecondActivity.class) 
startActivity(intent) 

在第二個活動,你可以獲取這個數據

@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    String first = DataTransporter.firstName; 
    String last = DataTransporter.lastName; 
} 

您可以刪除運輸類數據(如果需要)一次牽強。

+0

感謝您有用的意見! – user1884872

0

我更喜歡使用SharedPreferences保存我的數據,並用它在我的課,再加上他們將被保存到設備上,使它們可以在應用程序被殺害後也......下面是雅的例子!

//Some String that I should remember, I am just using the package name for now 
String app = this.getPackageName();/*This is going to be used more like a file to save my stuff to*/ 
//Setting our sharedpreferences 
SharedPreferences sha = sha = getApplicationContext().getSharedPreferences(app, SherlockActivity.MODE_PRIVATE); 


String myString = "This is the String that you want to save so you can use among your classes" 

//Now we call in an editor for that SharedPreferences so we can write and delete stuff from it . 

Editor edit = sha.edit(); 

//Now we insert our String. 
edit.putString("Something_you_can_remember" , myString);//You will need the "Something_you_can_remember" a few lines ahead , so remember it ! 
edit.apply(); //Or we can use edit.commit() , but I prefer apply() 

//Now our String is saved ! So lets read it ! 

String whatever = sha.getString("Something_you_can_remember" , "The String incase myString didn't even exist , saves you from a NullPointerException"); 

//Here we go ! Now we have our String saved and can be readable among the classes ! 

另外,如果你想刪除該字符串或無論在那裏你「放」,你可以叫

edit.remove("Something_you_can_remember"); //or edit.clear() to remove all the values stored ! 

希望這有助於!

相關問題