我有一个Android应用程序代码,可使用php脚本从mySQL数据库读取数据。第一次正确读取数据。但是,如果我从数据库手动更新数据库中的数据,则该应用程序将显示第一次运行代码时读取的数据。如果我更改了php脚本的网址,则android应用程序代码将能够读取更新的数据。下面是我的android代码,它从php读取数据。
Log.d("parserclass here", json);
中的值将始终显示上载php脚本时首次读取的数据。我已经通过使用Internet Explorer或其他Web浏览器尝试从mySQL读取数据来验证php脚本是正确的。
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpClient httpClient = new DefaultHttpClient();
// constructor
public JSONParser() {
}
public void shutdown(){
httpClient.getConnectionManager().shutdown();
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.d("parserclass here", json);
reader.reset();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}