【问题标题】:PrintWriter#println() throws a NullPointerException in the ThreadPrintWriter#println() 在线程中抛出 NullPointerException
【发布时间】:2014-01-08 17:54:16
【问题描述】:

我正在尝试使用PrintWriter#println(message) 发送String 消息,但是一旦我调用该线程,它就会引发异常。 我不知道这条消息是从哪里来的。我检查了消息是不是null,但不是这样。

import java.io.PrintWriter;

import android.util.Log;

public class Send_Client implements Runnable {
    private PrintWriter out;
    private String message=null;

    public Send_Client(PrintWriter out,String message) {
        this.out=out;
        this.message=message;
    }

    @Override
    public void run() {
        // the message is different from null
        // Problem to resolve
        out.println(message);
        out.flush();
        Log.d(MainActivity.TAG, "The message has been sent from Send_Client");
    }
}

这里是我调用线程的地方

    public class ClientDataService extends IntentService {
private static Socket socket=null;
private static final int SOCKET_TIMEOUT = 5000;

public static final String ACTION_CLIENT="Action_Client";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
String message=null;
private BufferedReader in=null;
public PrintWriter out=null;
/** Command to the service to receive a message */
static final int MSG_CLIENT = 2;

public ClientDataService(String name) {
    super(name);

}
public ClientDataService() {
    super("ClientDataService");
    }
@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(ACTION_CLIENT)) {
        int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
        String host=  intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
            try{
                Log.d(MainActivity.TAG, "ask for connection to the server");
                socket=new Socket();
                socket.bind(null);
                socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
                Log.d(MainActivity.TAG, "connection socket has been established");

                try{
                    in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    out= new PrintWriter(socket.getOutputStream());
                    Thread t1=new Thread(new Receive_Client(in));
                    t1.start();

                }catch(IOException e){
                    Log.d(MainActivity.TAG, "the client disconnect");

            } 

            }catch (UnknownHostException e) {
                Log.d(MainActivity.TAG, "impossible to connect to the host"+socket.getLocalSocketAddress());
            }catch (IOException e) {
                Log.d(MainActivity.TAG, "No Server Listening the port"+socket.getLocalPort());
            }

    }
      }
public PrintWriter getOutputstream(){
    return out;
}

 /**
     * Handler of incoming messages from UI Thread.
      */
     class IncomingHandler extends Handler {
    ClientDataService mservice;
    @Override
    public void handleMessage(Message msg) {

        switch (msg.what) {
            case MSG_CLIENT:
                 mservice=new ClientDataService();
                Log.d(MainActivity.TAG,"CDS has received the following message to send to the server"+(String)msg.obj);
                Log.d(MainActivity.TAG, "Get the Out value"+mservice.getOutputstream().toString());
                Thread t2= new Thread(new Send_Client(mservice.getOutputstream(),(String)msg.obj));
                t2.start();
                break;
            default:
                super.handleMessage(msg);
        }
    }
   }

   /**
   * Target we publish for clients to send messages to IncomingHandler.
   */
   final Messenger mMessenger = new Messenger(new IncomingHandler());

   /**
    * When binding to the service, we return an interface to our messenger
   * for sending messages to the service.
    */
   @Override
    public IBinder onBind(Intent intent) {
    Toast.makeText(getApplicationContext(), "binding client", Toast.LENGTH_SHORT).show();
    return mMessenger.getBinder();
  }

  }

【问题讨论】:

  • out 也是非空的吗?
  • NPE 到底是在哪里抛出的?在out.println(message) 行中?
  • outnull 时,NPE 被抛出该行的唯一可能性。所以请检查是否是这种情况。
  • 是的,我刚刚检查过,实际上问题出在了。
  • @Veger ,我刚刚修改了帖子。实际上我想使用在 onhandleIntent 中创建的“out”。但是当我尝试使用这个“out”时,应用程序崩溃了。你知道我该如何解决这个问题吗

标签: android exception android-intent android-service


【解决方案1】:

我会将其作为答案发布,因为评论有点长(即使我无法提供完整/直接的解决方案)。

出现问题的原因是:

  1. 当您在 IncomingHandler 中创建对象时,out 尚未在 ClientDataService 中设置
  2. 所以mservice.getOutputstream()返回null
  3. 你在Send_Client中使用。

您滥用ServerIntent,直接使用new ClientDataService()从它创建派生对象。

相反,您需要按照Android Service documentation

Intent intent = new Intent(this, HelloService.class);
startService(intent);

所以我想您需要阅读更多有关 android 服务的信息(文档中的大量信息对我来说很重要),以便在您的应用程序中正确使用它们。

【讨论】:

  • 我想我找到了问题,是的,事实上我尝试了这个解决方案,因为单独使用 out 时,它返回 null。由于传入的处理程序是 ClientDataService 的内部类,因此我只需放入 ClientDataService.this.out 并且通常它应该可以在不使用任何新 ClientDataService() 实例的情况下工作。非常感谢您的帮助@Veger
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多