Edit我解决了我的问题:刚刚用mysql_set_charset('utf8',$con);
替换了mysql_query('set names utf8');
($con是我的"mysql_connect"(
自从我添加了我的PHP文件
mysql_query('set names utf8');
我的安多利德应用程序崩溃了。在此之前,一切正常,但我在 JSON 请求中遇到了"öäü"的"空"问题,所以我需要在 php java 请求中添加"设置名称 utf8">
安卓错误日志:
Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
这是我在活动类中的空白:
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());
我的 API 连接器.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);
我发现当我组装数组然后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);