This code:
protected void initSingleton()
{
Singleton.initSingleton();
}
Is not executing before you try to get the instance, even if you are calling that function onCreate()
. Why are you instantiating the Singleton on a separate method instead of instantiating it inside the getInstance()
?
Change your code to look like this to avoid this kind of problem when you call the Singleton and the instance doesn't exist.
public static Singleton getInstance()
{
if(instance == null)
initSingleton();
return instance;
}
private static void initSingleton()
{
instance = new Singleton();
InetAddress serverAddr = null;
try
{
serverAddr = InetAddress.getByName(SERVER_IP);
}
catch (UnknownHostException e)
{
System.err.println("Fail when getting Server Address.");
}
try
{
socket = new Socket(serverAddr, SERVERPORT);
}
catch (IOException e)
{
System.err.println("Failed creating new socket.");
}
try
{
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
}
catch (IOException e)
{
System.err.println("EPIC FAIL HERE");
}
}
Main activity:
public class MainActivity extends Activity implements OnItemSelectedListener
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickon(View view)
{
Socket socket = Singleton.getInstance().getSocket();
try
{
PrintWriter out=Singleton.getInstance().getOutput();
out.println("0");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}