Created
November 10, 2015 20:16
-
-
Save mkiisoft/b8a177a4286aa9708cc0 to your computer and use it in GitHub Desktop.
Stackoverflow answer, "Singleton in Android"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.testSingleton; | |
import android.app.Activity; | |
import android.content.Intent; | |
import android.os.Bundle; | |
import android.widget.Toast; | |
public class ActivityA extends Activity { | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
//Show the string value defined by the private constructor | |
Toast.makeText(getApplicationContext(),Singleton.getInstance().getString(), Toast.LENGTH_LONG).show(); | |
//Change the string value and launch intent to ActivityB | |
Singleton.getInstance().setString("Singleton"); | |
Intent intent = new Intent(getApplicationContext(),ActivityB.class); | |
this.startActivity(intent); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.testSingleton; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.widget.Toast; | |
/** | |
* Created with IntelliJ IDEA. | |
* Date: 13/05/13 | |
* Time: 10:40 | |
*/ | |
public class ActivityB extends Activity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
//Show the string value of the singleton | |
Toast.makeText(getApplicationContext(),Singleton.getInstance().getString(), Toast.LENGTH_SHORT).show(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.testSingleton; | |
/** | |
* Created with IntelliJ IDEA. | |
* Date: 13/05/13 | |
* Time: 10:36 | |
*/ | |
public class Singleton { | |
private static Singleton mInstance = null; | |
private String mString; | |
private Singleton(){ | |
mString = "Hello"; | |
} | |
public static Singleton getInstance(){ | |
if(mInstance == null) | |
{ | |
mInstance = new Singleton(); | |
} | |
return mInstance; | |
} | |
public String getString(){ | |
return this.mString; | |
} | |
public void setString(String value){ | |
mString = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment