Created
June 18, 2016 15:52
-
-
Save ganeshachary/7b966f6d2e456ba083f6d57ccc0c8340 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