Java Android值未添加到Arraylist中

时间:2015-07-16 08:36:32

标签: java android arraylist

我正在与使用android studio的客户端创建套接字连接。我可以成功地在移动设备和服务器之间建立连接,我的第一个调试消息(Log.d("While Debugger", line))成功显示了来自服务器的输入数据。但是,arraylist似乎没有添加结果,而我的其他调试消息没有提供任何输出! 为了进一步说明,当我调用returnData()方法时,温度数组将返回null。 任何帮助将不胜感激,我将尽我所能回答有关我所写的问题。谢谢!

package com.mycompany.myfirstapp;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

/**
 * Created by seank on 15/07/2015.
 */
public class SocketExample {
    ArrayList<Double> temperature = new ArrayList<Double>();

public SocketExample() throws  IOException {

    String serverHostname = new String ("192.168.1.143");

    System.out.println ("Attemping to connect to host " +
            serverHostname + " on port 10007.");

    Socket echoSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    Log.d("Here", "Got to the streams");
    try {
        echoSocket = new Socket(serverHostname, 10007);
        in = new BufferedReader(new InputStreamReader(
                echoSocket.getInputStream()));
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: " + serverHostname);
        Log.e("Here","Don't know about host: " + serverHostname);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for "
                + "the connection to: " + serverHostname);
        Log.e("Here","Couldn't get I/O for "
                + "the connection to: " + serverHostname);
        System.exit(1);
    }

    String line;
    while( (line = in.readLine()) != null ) {
        Log.d("While Debugger", line);
        Double value = Double.parseDouble(line);
        temperature.add(value);
    }

    if(temperature.size() == 0) {
        Log.d("Numbers", "size = 0");
    }
    else {
        Log.d("Numbers", String.valueOf(temperature.size()));
    }

    if(String.valueOf(temperature.size()) == null) {
        Log.e("Numbers", "The temperature size is a null value");
    }
    // Close our streams
    in.close();
    out.close();
    echoSocket.close();
}

public ArrayList<Double> returnData() {
    return temperature;
}

    public static void main(String[] args) throws IOException {
        SocketExample socket = new SocketExample();
    }
}

1 个答案:

答案 0 :(得分:0)

我认为,你的程序在while循环中是阻塞的,因此你的下一个调试不会被执行。

您可以尝试在while循环中添加以下代码

if(temperature.size() == 0) {
    Log.d("Numbers", "size = 0");
}
else {
    Log.d("Numbers", String.valueOf(temperature.size()));
}