Java ServerSocket引发空指针异常

Java ServerSocket引发空指针异常,java,android,serversocket,Java,Android,Serversocket,我正在尝试在Android中通过Java套接字实现文件传输。它工作正常,但当我关闭应用程序时,它崩溃,控制台显示nullPointerException。我什么都试过了,但找不到问题!。我已将ServerSocket定义为类变量,并在检查服务器套接字的状态后在onDestroy()方法中将其关闭。这是我的密码: package com.vinit.airdrive; import java.io.BufferedInputStream; import java.io.DataInputStre

我正在尝试在Android中通过Java套接字实现文件传输。它工作正常,但当我关闭应用程序时,它崩溃,控制台显示nullPointerException。我什么都试过了,但找不到问题!。我已将ServerSocket定义为类变量,并在检查服务器套接字的状态后在onDestroy()方法中将其关闭。这是我的密码:

package com.vinit.airdrive;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
//Latest saved stub
@SuppressLint("SdCardPath")
public class MainActivity extends Activity {
    Socket socket=null;
    ServerSocket serversocket=null;
    ArrayList<File> fileArray=null;

    @SuppressLint("SdCardPath")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        File file1=new File(Environment.getExternalStorageDirectory()+"/airdrive/Sphere.pdf");
        File file2=new File(Environment.getExternalStorageDirectory()+"/airdrive/Robinson.pdf");
        File file3=new File(Environment.getExternalStorageDirectory()+"/airdrive/Conspiracy.pdf");
        File file4=new File(Environment.getExternalStorageDirectory()+"/airdrive/Expedition.pdf");
        File file5=new File(Environment.getExternalStorageDirectory()+"/airdrive/Xperia.pdf");
        fileArray=new ArrayList<File>();
        fileArray.add(file1);
        fileArray.add(file2);
        fileArray.add(file3);
        fileArray.add(file4);
        fileArray.add(file5);

        Thread trd = new Thread(new Runnable(){
              @Override
              public void run(){
                initializeServer();
                for (int i=0;i<=4;i++){
                    copyFile(fileArray.get(i), fileArray.get(i).getName());
                }
              }
            });
        trd.start();
    }

    private void initializeServer() {
        try {
            serversocket=new ServerSocket(4444);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("Listen failed", "Couldn't listen to port 4444");
        }
        try {
            socket=serversocket.accept();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.d("Acceptance failed","couldn't accept the server socket connection");
        }
    }

    private void copyFile(File file, String name) {
        FileInputStream fis;
        long filesize=file.length();
        try {
            fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            @SuppressWarnings("resource")
            DataInputStream dis = new DataInputStream(bis);
            byte[] mybytearray = new byte[16384];
            OutputStream os;
            os=socket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(name); //filename is also sent to client
            dos.writeLong(filesize); //file size is also sent to client
            long z=filesize;
            int n=0;

            while((z > 0) && (n = dis.read(mybytearray, 0, (int)Math.min(mybytearray.length, z))) != -1){
                  dos.write(mybytearray,0,n);
                  dos.flush();
                  z -= n;
                }
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (serversocket != null) {
            try {
                serversocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
编辑2:

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    if (serversocket != null && socket==null) {
        try {
            serversocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    super.onDestroy();
}

您的崩溃发生在以下位置:

os=socket.getOutputStream();
我猜您还需要关闭
套接字
对象。你可以在最后一个街区做

try {
    // .. your code here ..
} catch (Exception e) {
    // handle exception
} finally {
    if (socket != null) {
        socket.close()
    }
}
或者在
ondestory()
方法中,例如

@Override
protected void onDestroy() {

    if (socket != null) {
        try {
             socket.close();
        } catch (IOException e) {
             e.printStackTrace();
        }
    }

    if (serversocket != null) {
        try {
            serversocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // call the super method **after** you have closed your objects!
    super.onDestroy();
}

谢谢大家!!终于解决了这个问题。我只是在从套接字获取输出流之前插入了一个检查点。以下是代码片段:

if (socket!=null){
        os=socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(name); //filename is also sent to client
        dos.writeLong(filesize); //file size is also sent to client
        long z=filesize;
        int n=0;

        while((z > 0) && (n = dis.read(mybytearray, 0, (int)Math.min(mybytearray.length, z))) != -1){
              dos.write(mybytearray,0,n);
              dos.flush();
              z -= n;
            }
        }
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

请发布崩溃日志。您在哪一行获得异常?请参阅编辑部分。os=socket.getOutputStream();然后套接字为空。我不明白你为什么一开始没有提到所有这些信息。让我检查一下。。。我会在几分钟后给你回复的!:)注意我上次的编辑。同时尝试将
super.ondestory()
调用移动到方法的末尾。@dextor:不幸的是,问题仍然存在!我两个都试过了。。第83行仍有错误。@njzk2为什么不?尽管如此,我发现这是一个很好的做法。首先调用
super.onCreate()
,最后调用
super.onDestroy()。
if (socket!=null){
        os=socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(name); //filename is also sent to client
        dos.writeLong(filesize); //file size is also sent to client
        long z=filesize;
        int n=0;

        while((z > 0) && (n = dis.read(mybytearray, 0, (int)Math.min(mybytearray.length, z))) != -1){
              dos.write(mybytearray,0,n);
              dos.flush();
              z -= n;
            }
        }
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }