我已经按照这个链接成功地在 Android 中制作了单例类。 http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
问题是我想要一个对象。就像我有 Activity A 和 Activity B。在 Activity AI 中从 Singleton 访问对象class
。我使用该对象并对其进行了一些更改。
当我移动到 Activity B 并从 Singleton Class 访问对象时,它给了我初始化的对象并且不保留我在 Activity A 中所做的更改。还有其他方法可以保存更改吗?请高手帮帮我。这是MainActivity
public class MainActivity extends Activity {
protected MyApplication app;
private OnClickListener btn2=new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get the application instance
app = (MyApplication)getApplication();
// Call a custom application method
app.customAppMethod();
// Call a custom method in MySingleton
Singleton.getInstance().customSingletonMethod();
Singleton.getInstance();
// Read the value of a variable in MySingleton
String singletonVar = Singleton.customVar;
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(btn2);
}
}
这是NextActivity
public class NextActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
String singletonVar = Singleton.customVar;
Log.d("Test",singletonVar);
}
}
Singleton
班级
public class Singleton
{
private static Singleton instance;
public static String customVar="Hello";
public static void initInstance()
{
if (instance == null)
{
// Create the instance
instance = new Singleton();
}
}
public static Singleton getInstance()
{
// Return the instance
return instance;
}
private Singleton()
{
// Constructor hidden because this is a singleton
}
public void customSingletonMethod()
{
// Custom method
}
}
和MyApplication
public class MyApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
// Initialize the singletons so their instances
// are bound to the application process.
initSingletons();
}
protected void initSingletons()
{
// Initialize the instance of MySingleton
Singleton.initInstance();
}
public void customAppMethod()
{
// Custom application method
}
}
当我运行这段代码时,我得到了我已经在Singleton
World 中初始化的 Hello,然后我将它输入了它,MainActivity
并再次NextActivity
在 logcat 中显示了 Hello。我希望它再次展示世界NextActivity
。请帮我纠正这个问题。