2014-09-04 65 views
1

我使用Xamarin开发Android程序。 我的应用程序,他们通过使用例如该代码将数据传递给对方许多不同的活动:如何使用1意图在活动之间进行传输?

Intent myIntent = new Intent(this, typeof(ViewAccountActivity)); 
myIntent.PutExtra("loginedcustomer", JsonConvert.SerializeObject(loginedCustomer)); 
StartActivity(myIntent); 

,然后检索由

loginedCustomer = JsonConvert.DeserializeObject<Customer>(Intent.GetStringExtra("loginedcustomer")); 

现在我的问题是这样的数据,对于每一个过渡另一个活动,我必须做出意图,并把数据,并启动它意味着我必须检索数据,然后再次放置并开始我的新意图。 有没有更简单的方法来做到这一点? 像使用一个意图,只改变它在哪里?(在构造函数中) 谢谢

+0

如果您需要使用在许多活动同一个对象,你为什么不把那个对象在[Application class]中(http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android)?并在稍后,从唯一的检索? – 2014-09-04 12:20:01

+0

通过Intent的额外传递Messenger或ResultReceiver – pskink 2014-09-04 12:39:33

回答

0

您可以使用Application类来跨多个活动访问同一个对象。

public class TestApplication extends Application { 

    public TempClass tempClass; 

    public TestApplication() { 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     super.onCreate(); 
    } 

    public TempClass getTempClass() { 
     return tempClass; 
    } 

    public void setTempClass(TempClass tempClass) { 
     this.tempClass = tempClass; 
    } 
} 

现在,在您的活动:

//after setContentView 
testAppObj = (TestApplication) getApplication(); 
testAppObj.setTempClass(myTempClassObj); 

//retrieve as: 
TempClass obj = testAppObj.getTempClass(); 

希望这有助于。

PS: 您必须注册您的应用程序类在你的清单文件,就像您注册活动:

<application 
     android:name="com.pkg.test.TestApplication " /> 
+0

这个方法中的数据会在应用程序关闭时被删除吗?或者我可以将它们保存在文件中? – 2014-09-04 12:50:59

+0

他们将被删除。如果你想保存简单的字符串,你可以尝试[共享偏好](http://developer.android.com/reference/android/content/SharedPreferences.html)@saeedek – 2014-09-04 12:51:51

+0

谢谢你。但你知道如何应用这个到Xamarin(C#)?有一个应用程序对象,当我尝试投射到我的自定义类给我一个错误说,不能投掷 – 2014-09-04 14:47:22

相关问题