Skip to content

Instantly share code, notes, and snippets.

@pranavlathigara
Created February 3, 2017 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pranavlathigara/61b051d505a898a2b87957a0f5f7c8a6 to your computer and use it in GitHub Desktop.
Save pranavlathigara/61b051d505a898a2b87957a0f5f7c8a6 to your computer and use it in GitHub Desktop.
Stackoverflow answer, "Singleton in Android"
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);
}
}
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();
}
}
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