我正在尝试执行以下代码以使用 Web 服务从数据库中检索数据:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getData();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getData(){
TextView resultView = (TextView) findViewById(R.id.textView1);
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag","Error in http connection"+e.toString());
resultView.setText("Couldnt connect to database");
}
//converting to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result"+ e.toString());
}
//parse data
try{
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i = 0;i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s + "St.ID" + json.getString("StId") + "\n " +json.getString("StName") + "\n" + json.getString("StMail");
}
resultView.setText(s);
}
catch(Exception e){
Log.e("Log_tage", "Error Parsing Data"+e.toString());
}
}
但返回错误:无法连接到数据库。
这是输出 LogCat:
11-14 20:10:35.057:E/log_tag(5323):http 连接出错android.os.NetworkOnMainThreadException
11-14 20:10:35.057: E/log_tag(5323): 错误转换结果java.lang.NullPointerException: lock == null
11-14 20:10:35.057:E/Log_tage(5323):解析 Dataorg.json.JSONException 时出错:字符 0 处输入结束
我在一些网络服务上添加了一个 php 文件,它运行良好,但我认为它与 HttpPost URL 有关,HttpPost URL 是否有特定格式,或者它与网络服务中给出的 URL 相同?
PHP 文件:
<?php
$con = mysql_connect("HOST","USERNAME","PASSWORD");
if (!$con)
{
die('Could not Connect:'. mysql_error());
}
mysql_select_db("database_name",$con);
$result = mysql_query("SELECT * FROM table_name");
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
请帮忙。