0

我正在尝试将一些数据从我的 android 设备发送到MySQL database. 似乎数据库没有更新,并且ProgressDialogAsyncTask的没有完成。

所以这是我的 PHP 脚本

 <?php 
   mysql_connect("localhost","$username","$password") or die(mysql_error());
   mysql_select_db("databaseName");

   $pcn =   $_POST['PCN'];
   $date = $_POST['Date'] ;

   $query_add="INSERT INTO data (`pcn`,`date`) VALUES ('$pcn','$date')";
   $query_exec=mysql_query($query_add) or die(mysql_error()); 
   mysql_close()
 ?>

然后我的java代码:

protected void onPreExecute() {
      progressDialog=ProgressDialog.show(context,"Please Wait..","Sending data to database",false);
    }

  @Override
  protected String doInBackground(String... params) {


      try {
          httpclient = new DefaultHttpClient();
          httppost = new HttpPost("http://localhost/index.php");
          ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
          postParameters.add(new BasicNameValuePair("PCN", pcn));
          postParameters.add(new BasicNameValuePair("Date", date));

          httppost.setEntity(new UrlEncodedFormEntity(postParameters));                   
          HttpResponse response = httpclient.execute(httppost);
          Log.i("postData", response.getStatusLine().toString());
       }
       catch(Exception e)
       {
            Log.e(TAG, "Error:  "+e.toString());
       }  

    return "";
}

protected void onPostExecute(String result) {

        progressDialog.dismiss(); 
        Toast.makeText(context, "Finished", Toast.LENGTH_LONG).show(); 

}

在我的清单文件中:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

这是 LogCat 的输出

07-04 12:52:34.025: E/SendToServer(15167): Error:  org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused

我已经阅读了几个我不能使用的地方http://localhost,但是当我尝试时http://10.0.0.2它应该可以工作。

我不知道该怎么做,有人能指出我正确的方向吗?

更新

当我尝试10.0.2.2而不是LocalhostLogCat 输出时:

Error:  java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=10.0.2.2

更新 2

现在,当我使用http://10.0.2.2永不progressdialog完成时,logcat 也没有向我显示任何异常

更新 3

我想我知道为什么我的应用程序不更新我的数据库。我的手机在我的工作站之外的另一个无线网络中..

4

3 回答 3

1

你的问题是这条线,

httppost = new HttpPost("http://localhost/index.php");

Android 不理解 url 中的 localhost。

使用系统的静态 IP10.0.2.2代替localhost

于 2012-07-04T10:58:40.030 回答
0

Android 不要使用localhost,试试10.0.2.2

更多细节在这里

于 2012-07-04T11:05:00.817 回答
0

使用“10.0.2.2”时遇到的错误最常发生在10.0.0.2您必须使用时使用http://10.0.2.2

确保您正在使用:

httppost = new HttpPost("http://10.0.2.2/index.php");

希望这能解决您的问题。

于 2012-07-04T11:12:53.783 回答