1

我正在尝试执行以下代码以使用 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);
?>

请帮忙。

4

2 回答 2

1

HttpPost URL 没有特定的格式,它与 Web 服务中给出的 URL 相同。

您必须使用AsyncTask来解决“无法连接到数据库”错误。

这是您使用 AsynTask 的代码,您还必须TextViewonPostExecute方法中设置文本,如下所示:

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);
    }
}
于 2013-11-15T22:21:46.110 回答
0

通过使用 @Carlo 的代码并编辑以下代码行解决了问题并检索了数据:

HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");

到:

HttpGet httppost = new HttpGet("http://HOSTNAME/FILENAME.php");

正如我的代码中提到的,我想从不发布数据的 URL 中检索数据。

HttpPost > 用于向指定资源提交数据。HttpGet > 用于从指定资源中检索数据。

感谢你的帮助。

于 2013-11-16T16:35:49.327 回答