我已经点击了这个链接,并成功地在Android中制作了单例类。http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
问题是我想要一个单一的对象。就像我有活动A和活动B一样,在活动A中,我从单例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
}
}
当我运行这段代码时,我得到的是Hello,它是我在Singleton
中初始化的,然后是World,它是我在MainActivity
中提供的,并且再次在logcat中的NextActivity
中显示Hello。我想让它在NextActivity
中再次展现世界。请帮我改正这个错误。
https://stackoverflow.com/questions/16517702
复制相似问题