Skip to content

Instantly share code, notes, and snippets.

@mkiisoft
Created November 10, 2015 20:16
Show Gist options
  • Save mkiisoft/b8a177a4286aa9708cc0 to your computer and use it in GitHub Desktop.
Save mkiisoft/b8a177a4286aa9708cc0 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