gpt4 book ai didi

android - Android中的单例

转载 作者:IT老高 更新时间:2023-10-28 13:15:05 24 4
gpt4 key购买 nike

我已关注此链接并成功在 Android 中制作了单例类。 http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

问题是我想要一个对象。就像我有 Activity A 和 Activity B。在 Activity A 中,我从 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 中初始化的 Hello然后是我在 MainActivity 中给出的 World并再次在 NextActivity 中显示 Hello在日志中。我希望它在 NextActivity 中再次向世界展示.请帮我纠正这个问题。

最佳答案

提示:在 Android Studio 中创建单例类,右键单击您的项目并打开菜单:

New -> Java Class -> Choose Singleton from dropdown menu

enter image description here

关于android - Android中的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16517702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com