使用Java读取PHP echo输出时出错

时间:2016-07-01 18:33:20

标签: java php android

我的应用中出现以下错误

  

java.lang.NullPointerException:尝试调用虚方法' java.lang.String java.lang.Object.toString()'在空对象引用上

启动HTTP连接的JAVA代码如下所示:

boolean l = true;
String[] ergebnisArray = new String[100];
for(int i = 0; i < ergebnisArray.length; i++) {
    ergebnisArray[i] = "";
}
String count = "0";
if(l) {
    try {
        String login_url = "http://192.168.178.82:8080/webapp/test.php";
        URL url = new URL(login_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        OutputStream outputStream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        String data = URLEncoder.encode("count", "UTF-8") + "=" + URLEncoder.encode(count, "UTF-8");
        bufferedWriter.write(data);
        bufferedWriter.flush();
        bufferedWriter.close();
        outputStream.close();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
        String response = "";
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            response += line;
        }
        bufferedReader.close();
        inputStream.close();
        httpURLConnection.disconnect();
        if (response != "") {
            int c = Integer.parseInt(count);
            ergebnisArray[c] = response;
            c++;
            count = Integer.toString(c);
        } else {
            l = false;

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return ergebnisArray;

最后是PHP代码:

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webdb";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$zaehler = $_POST["count"];

$sql = "SELECT * FROM stundenplan";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    // output data of each row
    while($row = $result->fetch_assoc() ) {
        for ($i = 0; $i <= (int)$zaehler; $i++) {
        $output =  "".$row["Lehrer"]." ".$row["Klasse"]." ".$row["Stunde"];
        }
    }

} else {
    echo "";
}
echo $output;
$conn->close();
?>

提前致谢

1 个答案:

答案 0 :(得分:0)

你需要在函数外部声明$ output然后将数据放入函数中,或者你可以在for循环中打印它。 我认为存在可变范围的问题,例如全局或本地。