我在onCreate中使用它时线程运行正常,但是当我启动Thread onClick时,应用程序崩溃了?

时间:2016-01-12 14:36:04

标签: java android multithreading server

我有一个局域网游戏的纸牌游戏。代码在PC上工作正常,但现在我将代码转移到Android。我遇到了一个奇怪的问题。

我在线程上主持一个游戏,通过按钮点击启动它不需要。球员继承人onClick方法:

 public void onClick(View v) {
            if(txtPlayers.getText().toString()!=null){
                int pl=Integer.parseInt(txtPlayers.getText().toString());
                Toast.makeText(MainActivity.this,"Server Started",Toast.LENGTH_LONG).show();
                new Thread(new GameServer(pl)).start();
            }
            else
            {
                Toast.makeText(MainActivity.this,"Enter Players",Toast.LENGTH_LONG).show();
            }
        }

在上面的代码中,我启动了GameServer的可运行接口,如下所示:

public class GameServer implements Runnable {
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private int maxClientsCount,port;
private  ClientThread[] threads;
private  Turn turn;
private  SumGame sg;
public final String TAG = "com.codechefamit.min";

GameServer(int players){
    maxClientsCount=players;
    port=7777;
    turn=new Turn(maxClientsCount);
    sg=new SumGame(maxClientsCount);
    threads=new ClientThread[maxClientsCount];
}

public void run() {
    try {
        Log.i(TAG,"Listening.....");
        serverSocket = new ServerSocket(port);
    } catch (IOException e) {
        System.out.println(e);
    }
    int count=0;
    while (count<maxClientsCount) {
        try {
            clientSocket = serverSocket.accept();
            int i = 0;
            for (i = 0; i < maxClientsCount; i++) {
                if (threads[i] == null) {
                    threads[i] = new ClientThread(clientSocket, threads,turn,count+1,sg);
                    count++;
                    Log.i(TAG,count+" Connected");
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    Log.i(TAG,"Starting Clients");
    for (int i = 0; i < maxClientsCount; i++)
        threads[i].start();
}

}

GameServer为每个客户端请求启动一个新线程。当我在My MainActivity onCreate()中启动GameServer Thread时,此代码运行正常但是当我将相同的代码复制到按钮时单击我的应用程序崩溃。

主持游戏的客户也从MainActivity加入游戏。这在我在onCreate中启动GameServer线程时有效。我做错了什么?

01-12 20:34:21.252  22250-22741/? E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2419
java.lang.NullPointerException
        at com.codechefamit.min_sumandroidclient.ClientThread.run(ClientThread.java:57)

0 个答案:

没有答案