Android JSON请求:由“utf8”引起的应用程序崩溃?

时间:2014-12-22 22:17:40

标签: php android json request

修改 我解决了我的问题:刚刚用mysql_query('set names utf8');替换mysql_set_charset('utf8',$con);($ con是我的“mysql_connect”)


因为我在我的PHP文件中添加了

mysql_query('set names utf8');

我的Andorid App崩溃了。在此之前,所有工作正常但我在我的JSON请求中有一个“null”问题与“öäü”所以我需要在我的php java请求中添加'set names utf8'

Android错误日志:

 Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference

这是我在Actitity Class中的空白:

public void setTextToTextViewText(JSONArray jsonArray) {

    String s = "";
    JSONObject json = null;
    try {
        json = jsonArray.getJSONObject(0);
        s = json.getString("Eventbeschr") + "\n" + "\n" +
                "Spiel: " + json.getInt("Spiel") + "\n" +
                "Beginn: " + json.getString("EventDatum") + "\n" +
                "Max. Teilnehmer: " + json.getInt("maxTeilnehmer") + "\n" +
                "\n";
    } catch (JSONException e) {
        e.printStackTrace();
        this.textView_eventTitel.setText(R.string.eventinfo_getting_text_error_body);
    }
    this.textView_eventInfo.setText(s);

}

private class GetLastEventTask extends AsyncTask<ApiConnector, Long, JSONArray> {

    @Override
    protected JSONArray doInBackground(ApiConnector... params) {

        return params[0].GetLatestEvent();
    }

    @Override
    protected void onPostExecute(JSONArray jsonArray) {

        setTextToTextViewHead(jsonArray);
    }


}

在我的onCreate中,我打电话给:

new GetLastEventTask().execute(new ApiConnector());

我的ApiConnector.java文件

public class ApiConnector {
    public JSONArray GetLatestEvent()
    {
        String url = "MY URL TO PHP FILE";


        HttpEntity httpEntity = null;

        try
        {

            DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);

            httpEntity = httpResponse.getEntity();



        } catch (IOException e) {
            e.printStackTrace();
        }


        // Convert HttpEntity into JSON Array
        JSONArray jsonArray = null;

        if (httpEntity != null) {
            try {
                String entityResponse = EntityUtils.toString(httpEntity);

                Log.e("Entity Response  : ", entityResponse);

                jsonArray = new JSONArray(entityResponse);

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return jsonArray;
    }
}

Maby有用,但这里也是我的PHP文件的主要部分:

    mysql_select_db("DB NAME", $con);

$result=mysql_query('set names utf8');

$result = mysql_query("SELECT * FROM event ORDER BY EventID desc limit 1");

while($row = mysql_fetch_assoc($result))
{
    $output[]=$row;

}
print(json_encode($output));

mysql_close($con);

1 个答案:

答案 0 :(得分:0)

我发现当我组装数组然后对它们进行json_encode时,我必须对数组中的值进行utf8_encode以防止它偶然发生错误。

尝试:

$output[] = utf8_encode($row);

编辑:

很抱歉没有抓到第一次读取时$ row是一个数组。为此,您需要更加零碎地构建数据集,在此处逐渐增加一个键,并手动将所需的每个字段添加到数组中(显然用真实的字符替换我的占位符字段名称)。

$key = 0;
while($row = mysql_fetch_assoc($result))
{
    $output[$key]['field1'] = utf8_encode($row['field1']);
    $output[$key]['field2'] = utf8_encode($row['field2']);
    $key++;
}

另一个替代方案可能是像array_map这样的函数对已组装的数组进行编码:

while($row = mysql_fetch_assoc($result))
{
    $output[]=$row;
}
$output = array_map("utf8_encode", $output);