0

我正在将外部数据库中的值检索到一个 android 应用程序中,该应用程序对服务器上的服务进行调用。这是php文件:

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (!$mysqli) {
    die('Connect Error (' . mysqli_connect_errno() . ') ' . sqli_connect_error());
}

$q=mysqli_query($mysqli, "SELECT title FROM post WHERE UPPER(title) LIKE UPPER('%" . $_REQUEST['searchThis'] . "%')");

while($e=mysqli_fetch_assoc($q)){
    $output[]=$e;
}

print(json_encode($output)); 
mysqli_close();

这就是我的班级所做的(我只写了重要的代码):

try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
}
catch(Exception e){
    Log.e("CONNECTION_ERROR", "Error in http connection "+e.toString());
}

try{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    result=sb.toString();

        ///-------------SYSTEM OUTS---------------

    System.out.println(result);
    System.out.println(result.getClass().getName());
}
catch(Exception e){
    Log.e("BUFFER_ERROR", "Error converting result "+e.toString());
}

//------------------PROBLEMS---------------
if(result.equalsIgnoreCase("null")){
    list.add("empty");
}

else{
    try{
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            //Log.i("result",json_data.getString("title"));
            String title = json_data.getString("title");
            list.add(title);
        }
    }
    catch(JSONException e){
        Log.e("DATA_PARSING_ERROR", "Error parsing data "+e.toString());
    }
}
return list;

}

我已经尝试过日志和打印,我得到的是:

null //FOR System.out.println(result);
java.lang.String //for System.out.println(result.getClass().getName());

它在服务器上的 php 服务返回某些内容时起作用,问题是当我将结果与“null”进行比较时,即使结果是值为“null”的字符串,它也总是错误的。然后我当然会遇到 JSON 异常,因为结果不是有效的转换格式。这里可能有什么问题?

4

1 回答 1

2

您的代码似乎没有考虑您附加的尾随换行符('\n')。

You can either remove the appending of the newline character ('\n') in the while loop or remove it when you check for "null".

于 2013-02-14T15:24:23.303 回答