3

我正在阅读有关如何使用 php 接口通过 Internet 将 android 连接到 mysql 数据库的教程。我按照它说的做了一切。

php代码是这样的:

  $q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
  while($e=mysql_fetch_assoc($q))
  $output[]=$e;

  print(json_encode($output));

  mysql_close();
?>

java代码是这样的:

String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));

//http post
try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
}catch(Exception e){
    Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();

    result=sb.toString();
}catch(Exception e){
    Log.e("log_tag", "Error converting result "+e.toString());
}

//parse json data
try{
    JSONArray jArray = new JSONArray(result);
    for(int i=0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            Log.i("log_tag","id: "+json_data.getInt("id")+
                    ", name: "+json_data.getString("name")+
                    ", sex: "+json_data.getInt("sex")+
                    ", birthyear: "+json_data.getInt("birthyear")
            );
    }
}
}catch(JSONException e){
    Log.e("log_tag", "Error parsing data "+e.toString());
}

现在的问题是它给了我一个错误,即变量“is”不存在!我该怎么办?

本教程来自网站 helloandroid.com:http://www.helloandroid.com/tutorials/connecting-mysql-database

4

1 回答 1

2
try{
    InputStream is = entity.getContent();
    ...
    ...
} //'is' goes out of scope here! 

范围仅限于第一个 try-catch 块,因此is在第二个中不可用。

做:

InputStream is = entity.getContent(); // 'is' now accessible in both try-catch
HttpEntity entity = response.getEntity(); // 'entity' is now accessible in both try-catch
try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    ...
    ...
}
于 2012-11-04T21:31:08.927 回答