1. ホーム
  2. android

Androidにおけるシングルトン

2023-11-04 11:24:32

質問

このリンクをたどって、Androidでシングルトン・クラスを作成することに成功しました。 http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

問題は、単一のオブジェクトが欲しいことです。例えば、アクティビティAとアクティビティBがあります。 class . 私はそのオブジェクトを使用し、それにいくつかの変更を加えました。

アクティビティBに移動し、シングルトンクラスからオブジェクトにアクセスすると、初期化されたオブジェクトが得られ、アクティビティ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 で初期化したHelloが表示され、Worldが表示されます。 MainActivity で、再び Hello を表示します。 NextActivity をlogcatで表示します。 で再びworldを表示させたいのですが NextActivity . これを修正するために私を助けてください。

どのように解決するのですか?

EDIT :

AndroidにおけるSingletonの実装は、quot;safe"ではありません( こちらをご覧ください のようなこの種のパターンに特化したライブラリを使用する必要があります。 ダガー のようなこの種のパターン専用のライブラリや、ライフサイクルとインジェクションを管理するための他のDIライブラリを使用する必要があります。


あなたのコードから例を投稿してもらえますか?

このgistを見てみてください。 https://gist.github.com/Akayh/5566992

これは動作しますが、非常に迅速に実行されました。

MyActivity : 初めてシングルトンを設定 + privateコンストラクタでmString属性("Hello")を初期化して値("Hello")を表示する。

mStringに新しい値 : "Singleton"を設定します。

アクティビティBを起動し、mStringの値を表示させると、"Singleton"が現れます...