Android - Create a Socket in Singleton

Asked

Viewed 122 times

0

Good night, I’m developing an android game where to play online have to connect to the server. At first I was trying to create sockets in an Activity where the game will occur, but the app was crashing when creating. After some research, I saw that they advised to create a Singleton and in this Singleton I created a Socket. The problem is that when calling this Singleton the app continues to crash when the Socket part arrives. Below, I leave the codes attached.

public class SingletonConnection extends OnlineGame {
private Socket socket;
private SingletonConnection() throws IOException {
    InetAddress serverAddr =InetAddress.getByName(hostname);
    this.socket = new Socket(serverAddr, server_port); //CRASHA AQUI
    this.inFromServer = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
    this.outToServer = new PrintWriter(this.socket.getOutputStream(),true);

}

public static SingletonConnection getSingletonConnection() throws IOException {
    if (ref == null)
        // it's ok, we can call this constructor
        ref = new SingletonConnection();
    return ref;
}

public Object clone()
        throws CloneNotSupportedException
{
    throw new CloneNotSupportedException();
    // that'll teach 'em
}
public void WriteToSocket(String string){
    this.outToServer.println(string);
}
public String ReadFromServer() throws IOException {
    return this.inFromServer.readLine();
}
private static SingletonConnection ref;
private static BufferedReader inFromServer;
private static PrintWriter outToServer;
public static final int server_port = 6000;
public static final String hostname = "192.168.1.65";

}

And I call this class from here

public void getInformationFromServer() throws IOException {
    SingletonConnection conect = SingletonConnection.getSingletonConnection();

    try {
        String playerString = conect.ReadFromServer();
        String[] players = playerString.split(",");
        initPlayers(players);
        String cardString = inFromServer.readLine();
        String playedCard = inFromServer.readLine();
        initDeck(cardString,playedCard);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

The Mistake you give me:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.martins.highcards, PID: 5497
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.martins.highcards/com.example.martins.highcards.OnlineGame}: android.os.NetworkOnMainThreadException
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
                  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
                  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
                  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
                  at java.net.Socket.connect(Socket.java:586)
                  at java.net.Socket.connect(Socket.java:535)
                  at java.net.Socket.<init>(Socket.java:427)
                  at java.net.Socket.<init>(Socket.java:210)
                  at com.example.martins.highcards.SingletonConnection.<init>(SingletonConnection.java:19)
                  at com.example.martins.highcards.SingletonConnection.getSingletonConnection(SingletonConnection.java:28)
                  at com.example.martins.highcards.OnlineGame.getInformationFromServer(OnlineGame.java:93)
                  at com.example.martins.highcards.OnlineGame.onCreate(OnlineGame.java:66)
                  at android.app.Activity.performCreate(Activity.java:6664)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                  at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
  • By error, you are trying to start a network process in the main class, android does not allow it, see if that article helps you solve.

  • Thank you very much, it helped :)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.