我正在尝试执行以下代码,以便使用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 connectionandroid.os.NetworkOnMainThreadException错误
11-14 20:10:35.057:E / log_tag(5323):转换resultjava.lang.NullPointerException时出错:lock == null
11-14 20:10:35.057:E / Log_tage(5323):错误解析Dataorg.json.JSONException:字符0处的输入结束
我在某些网络服务上添加了一个php文件并且运行良好,但我认为这是关于HttpPost URL,HttpPost URL是否有特定格式,或者它与Web服务中给出的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);
?>
请帮助。
答案 0 :(得分:1)
HttpPost网址没有特定的格式,它与网络服务中提供的网址相同。
您必须使用AsyncTask来解决“无法连接到数据库”错误。
以下是使用AsynTask的代码,您还必须在TextView
方法中设置onPostExecute
的文字,如下所示:
RetrievingDataFromDatabase retrievingTask;
TextView resultView;
String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrievingTask = new RetrievingDataFromDatabase();
retrievingTask.execute((Void) null);
}
@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(){
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 {
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");
}
}
catch(Exception e) {
Log.e("Log_tage", "Error Parsing Data" + e.toString());
}
}
class RetrievingDataFromDatabase extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
getData();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
resultView.setText(s);
}
}
答案 1 :(得分:0)
使用@Carlo的代码并编辑以下代码行来解决问题并检索数据:
HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");
为:
HttpGet httppost = new HttpGet("http://HOSTNAME/FILENAME.php");
如我的代码中所述,我想从URL中检索数据而不是发布数据。
HttpPost&gt;用于将数据提交到指定的资源。 HttpGet&gt;用于从指定资源中检索数据。
感谢大家的帮助。