0

As the title suggests, I am trying to create a singleton class for maintaining a TCP socket across different activities in my application. I am almost an absolute beginer to this and would really appreciate someone pointing me in the right direction.

UPDATE:

Here is the code for the class that I wrote:

public static ConnectionManager getInstance() {
    if(instance == null) {
    instance = new ConnectionManager();
    }
   return instance;
}



public void send(String str){

    try{
        PrintWriter out = new PrintWriter(new BufferedWriter(
        new OutputStreamWriter(access_point.getOutputStream())),true);
        out.println(str);
    }

    catch(IOException e){       
        e.printStackTrace();
    }


}

}

AND HERE IS HOW I CALLED IT ON ONE OF THE ACTIVITIES

private static ConnectionManager command = ConnectionManager.getInstance();
.........
command.send("Turn on");
  • From your question its not clear where you are stuck. But if you are going for Singleton design pattern, you can go for 'enum' based singleton. http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java – VishalDevgire Jun 24 '14 at 14:33
  • @VishaID I am making a simple app that sends strings over WiFi. Since I have several activities, once I go back to the main UI the connection is lost. From some research that I did it is highly recommended to use a singleton class that handles the socket and that can be accessed by all my activities. I hope this is more clear. Please excuse any mistakes or misconceptions, since I am very new to these concepts. – user3698584 Jun 24 '14 at 14:40
  • Seems similar to http://stackoverflow.com/questions/7582972/android-auth-keep-http-connection-use-connection-in-few-activity – Marc Van Daele Jun 24 '14 at 14:52
  • @MarcVanDaele Yes, it is similar, but instead I just connect to a server and send data to it. The link is quite useful, thank you ! – user3698584 Jun 24 '14 at 14:58
  • I tried the method that @MarcVanDaele suggested but did not manage anything. My app crashes now. I posted my code in the question above and would highly appreciate if someone had a look at it. – user3698584 Jun 24 '14 at 15:44
  • where does your app crashes? please add logcat output. – Marc Van Daele Jun 25 '14 at 07:53

0 Answers0