简体   繁体   中英

How can I stop my android app from force closing when it cant connect to my server?

My Android app connects to my server and when I have my server program running it works fine, But when it stopped and my app tries to connect to the server I want to display a toast message or something to the user. But firstly I have to prevent my application from force closing when the server is offline.

This is the error I get

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)

and this is the code where the connection is made to the server. It called from a different class

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;
    }
}

Add a null check to your try block. You should almost always check for null - it's just good practice.

eg:

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 

Note that this doesn't fix your code - there's another problem here.

You're probably going to get a null pointer exception in your code before the finally block, but because you have a finally block, you only see the exception from that block.

You'll want to do the null check before you call getInputStream() or getOutputStream() - or you can catch the NPE and handle it.

You're output stream is null when you try to close it. Moving its initialization outside of the first try block should fix the NullPointerException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM