我需要在Android中选择 MySql 到 Spinner 的数据。
我不知道错误在哪里,我怎么能解决这个问题。
public void selectfromclass(){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
String test= cyclespiner.getText().toString();
Log.d("toooooooooooooooooooooooooooooooop",test);
nameValuePairs.add(new BasicNameValuePair("name", test));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/getclassprof.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getActivity(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
// sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json=new JSONObject(result);
JSONArray JA = json.getJSONArray("matier");
/// JSONObject json = null;
roll_no = new String[JA.length()];
name = new String[JA.length()];
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
name[i] = json.getString("class");
}
spinner_fn();
} catch (Exception e) {
这是代码php
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$name=$_POST['name'];
$response["matier"] = array();
$r=mysql_query("SELECT class FROM classadmin WHERE cycle= '".$name."'",$con);
while($row=mysql_fetch_array($r))
{
$product["class"] = $row["class"];
array_push($response["matier"], $product);
//echo $fin."<br>";
}
print(json_encode($response));
mysql_close($con);
?>
这是json的结果
{"matier":[{"class":"azerty"}]}
答案 0 :(得分:1)
问题出在这里
while ((line = reader.readLine()) != null) {
// sb.append(line + "\n");
}
对sb.append
进行评论时,您没有使用从网络获取的数据填写StringBuilder
,并将其留空。空字符串不是有效的JSON,这会导致您的异常。由于您仍在使用Apache HttpClient,因此将Entity
转换为String的最简单方法是使用,
EntityUtils.toString(entity)
编辑:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/getclassprof.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getActivity(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
// here goes the code to parse result