jme*_*ase 2 c# android xamarin.android
我需要在登录时存储一些可用于应用程序中其他活动的信息.我试过创建一个单独的类:
public class MyApp : Application
{
private string siteID;
public string getSite()
{
return siteID;
}
public void setSite(string s)
{
siteID = s;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的登录活动中设置站点ID:
MyApp ma = new MyApp();
ma.setSite("IT-TEST");
Run Code Online (Sandbox Code Playgroud)
然后在另一个活动中尝试再次获取该值:
MyApp ma = new MyApp();
var site = ma.getSite();
Toast.MakeText(this, site, ToastLength.Long)
.Show();
Run Code Online (Sandbox Code Playgroud)
但这部分总是返回空白.我错过了什么?
问题是你MyApp每次实例化一个实例,所以那里没有数据持久性.有许多方法可以在应用程序中共享数据,但是您可以使用几种方法.
存储简单键/值对的一个好方法是使用Android的内置首选项系统.在活动中,您可以执行以下操作:
var settings = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
var editor = settings.Edit();
editor.PutString("key", "value");
editor.Commit();
var value = settings.GetString("key", null);
Run Code Online (Sandbox Code Playgroud)
另一种方法是子类Application,它将在整个应用程序中充当全局应用程序类:
[Application]
public class MyApplication : Application
{
public static string StaticString { get; set; }
public string InstanceString { get; set; }
public MyApplication(IntPtr handle, JniHandleOwnership transfer)
: base(handle, transfer)
{
}
}
Run Code Online (Sandbox Code Playgroud)
通过设计,将在整个应用程序中运行此类的一个实例.在Activity中,您可以通过将活动的Application属性强制转换为自定义类来访问类上的实例数据:
var instanceValue = ((MyApplication) Application).InstanceString;
Run Code Online (Sandbox Code Playgroud)
或者,您也可以在类上使用静态属性,如果这对您的情况更有效:
var staticValue = MyApplication.StaticString;
Run Code Online (Sandbox Code Playgroud)