当它无法连接到我的服务器时,如何阻止我的Android应用程序强行关闭?

时间:2015-03-11 16:28:06

标签: java android sockets server

我的Android应用程序连接到我的服务器,当我运行我的服务器程序时,它工作正常,但当它停止并且我的应用程序尝试连接到服务器时,我想向用户显示Toast消息或其他内容。但首先,当服务器脱机时,我必须阻止我的应用程序强行关闭。

这是我得到的错误

Process: project.sharethefare, PID: 27120
    java.lang.RuntimeException: Unable to start activity ComponentInfo{project.sharethefare/project.sharethefare.Share}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.ObjectInputStream.close()' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5834)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.ObjectInputStream.close()' on a null object reference
            at project.sharethefare.ServerConnect.run(ServerConnect.java:95)
            at project.sharethefare.Share.onCreate(Share.java:51)
            at android.app.Activity.performCreate(Activity.java:6221)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5834)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)

这是与服务器建立连接的代码。它来自另一个班级

public class ServerConnect{
    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    double message;
    ServerConnect(){}
    String TAG = "ShareTheFare";
    Share s;
    HomeScreen home = new HomeScreen();
    public static Double matchLocLat,matchLocLong,matchDesLat,matchDesLong;

    void run(){
        s = new Share();
        double curlat = home.curLat;         //Shanowen
        double curlong =home.curLong;
        double deslat = home.desLat;       //Parnell Street
        double deslong =home.desLong;

        /*double curlat = -37.862200;
        double curlong = 144.896377;
        double deslat = -37.860845;
        double deslong = 144.894252;*/

        try{
            //1. creating a socket to connect to the server
            requestSocket = new Socket("178.62.125.141",4444 );   //178.62.125.141
            System.out.println("Connected to localhost in port 2004");
            //2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            int count=0;
            //3: Communicating with the server
            while(count<5){                                    //this should break from server when the user recieves the 4 long and lats from server
                try{
                    message = (Double)in.readObject();
                    System.out.println("serverSent>" + message);
                    if(count==0){
                        //System.out.println("server>" + message);

                        sendMessage(curlat);
                        Log.d(TAG,"1");

                        sendMessage(curlong);
                        Log.d(TAG,"2");
                        sendMessage(deslat);
                        Log.d(TAG,"3");
                        sendMessage(deslong);
                        Log.d(TAG,"4");
                    }
                    if(message==1234.5){
                        //call the method to print out a toast saying no match found
                    }
                    else {
                        if (count == 1) {
                            matchLocLat = message;
                        }
                        if (count == 2) {
                            matchLocLong = message;
                        }
                        if (count == 3) {
                            matchDesLat = message;
                        }
                        if (count == 4) {
                            matchDesLong = message;

                        }
                    }


                    count++;
                    //System.out.println("Count: " + count);

                }
                catch(ClassNotFoundException classNot){
                    //S
                }
            }
        }
        catch(UnknownHostException unknownHost){
            System.err.println("You are trying to connect to an unknown host!");
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
    void sendMessage(Double msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
            //System.out.println("client>" + msg);
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }

    double getlat(){
        return matchLocLat;
    }

    double getlong() {
        return matchLocLong;
    }
}

2 个答案:

答案 0 :(得分:1)

在try块中添加空检查。你应该几乎总是检查无效 - 这只是一个好习惯。

例如:

try {
    if (requestSocket != null) { // this will be null if your server is offline when you tried to connect
        in.close();
        out.close();
        requestSocket.close();
    }
} // other stuff 

请注意,这并不能解决您的代码问题 - 这里还有另一个问题。

您可能会在之前在finally块中获得空指针异常,但由于您有一个finally块,因此您只能看到该块中的异常。

您希望在致电getInputStream()getOutputStream()之前进行空检查 - 或者您可以抓住NPE并处理它。

答案 1 :(得分:-1)

尝试关闭时,输出流为空。将其初始化移到第一个try块之外应修复NullPointerException。