我正在开发一个需要我连接到 mysql 数据库并从中检索信息的 android 应用程序。我正在使用 php 脚本连接到服务器并对其进行查询,然后以 json 格式输出结果:
if(!mysql_connect($mysql_host,$mysql_user,$mysql_pass) || !mysql_select_db($mysql_db)){
die($conn_error);
}
$q=mysql_query("SELECT * FROM food");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
这是我使用 HttpGet 获取数据并将其转换为字符串的 java 代码。然后它意味着解析数据并将其显示在屏幕上。
public class HttpExample extends Activity {
TextView httpStuff;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class GetMethodEx {
public String getInternetData() throws Exception {
BufferedReader in = null;
String data = "";
String returnString = null;
// httpGet
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://10.0.2.2/connect.php");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
// return data;
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "Foodname: " + json_data.getString("food"));
// Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
}
它正在做我想做的一切,除了解析数据。当我只想要食物名称时,它只是在屏幕上显示数据库的全部内容。有人可以帮忙吗?谢谢
编辑:这是我的 php 脚本的 json 输出的屏幕截图