Android应用无法将数据发送到远程服务器

时间:2013-03-09 16:00:32

标签: php android mysql database wamp

我正在创建一个只使用POST metod将数据发送到数据库的应用程序。我遇到的问题是应用程序在必须发送时不会做任何事情:没有崩溃,没有错误,没有。我已经单独测试了PHP代码并且它可以工作,所以我确信问题出现在代码中但我找不到它。你能帮助我吗?我很抱歉没有英语的var语言。

Android代码:

public class AggiungiProdotto extends Activity {

  private static String indirizzo = "http://10.0.2.2/tesina/Aggiungi_Ordinazione";


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aggiungi_prodotto);
    new AggiungoOrdinazione().execute();
  }

  private class AggiungoOrdinazione extends AsyncTask < String, Void, String > {

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
    }

    @Override
    protected String doInBackground(String...arg0) {
      InputStream is = null;
      String result = "";
      JSONObject jsonResult = null;
      TextView tv;
      //Intent intent = getIntent();
      String Nome = new String();

      //String Tavolo = intent.getStringExtra("Tavolo");
      int NumTavolo = 1;
      String Tavolo = Integer.toString(NumTavolo);
      Nome = "ciao";

      HttpPost httppost = new HttpPost(indirizzo);

      HttpParams httpParams = new BasicHttpParams();

      int timeOutConnection = 5000;
      HttpConnectionParams.setConnectionTimeout(httpParams, timeOutConnection);
      int timeoutSocket = 5000;
      HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
      HttpClient httpclient = new DefaultHttpClient(httpParams);

      List < NameValuePair > Comanda = new ArrayList < NameValuePair > ();
      Comanda.add(new BasicNameValuePair("Nome", Nome));
      Comanda.add(new BasicNameValuePair("Tavolo", Tavolo));


      try {
        httppost.setEntity(new UrlEncodedFormEntity(Comanda));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuilder sb = new StringBuilder();
        String line = null;
        while((line = reader.readLine()) != null) {
          sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        jsonResult = new JSONObject(result);



      } catch(UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch(ClientProtocolException e) {
        e.printStackTrace();
      } catch(IOException e) {
        e.printStackTrace();
      } catch(JSONException e) {
        e.printStackTrace();
      }

      return null;
    }
  }
  protected void onPostExecute() {
  }
}

PHP代码:

$Nome;
$Tavolo;

$Risposta = array();

//Apro la connessione con il server mySQL

$Conn = mysql_connect("localhost", "root", "");
if(!$Conn) {
    die('Errore di connessione: '.mysql_error());
}


//Seleziono il mio database
$DBS = mysql_select_db('ordinazioni', $Conn);
if(!$DBS) {
    die('Accesso al database non riuscito: '.mysql_error());
}

//echo "Mi sono connesso!";

$Nome = $_POST['Nome'];
$Tavolo = $_POST['Tavolo'];

$strSQL = mysql_query("INSERT INTO Comande (Nome, Tavolo) VALUES ('$Nome', '$Tavolo')");

if($strSQL) {
    $Risposta["Esito"] = 1;
    $Risposta["Messaggio"] = "Comanda aggiunta!";
    echo json_encode($Risposta);
    echo "Ho aggiunto!";
}
else {
    $Risposta["Esito"] = 0;
    $Risposta["Messaggio"] = "Errore nell'aggiunta!";
    echo "Non ho aggiunto!";
    echo json_encode($Risposta);
}

?>

清单:

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="17" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.gabriele.tesina.Menu_Iniziale"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.gabriele.tesina.Listino"
        android:label="Il Nostro Menù" >
    </activity>
    <activity
        android:name="com.gabriele.tesina.Ordinazioni_Cuoco"
        android:label="Le pietanze da preparare" >
    </activity>
    <activity
        android:name="com.gabriele.tesina.Ordinazioni_Pizza"
        android:label="Le pizze da infornare" >
    </activity>
    <activity android:name="com.gabriele.tesina.Primi" />
    <activity android:name="com.gabriele.tesina.Secondi" />
    <activity android:name="com.gabriele.tesina.Contorni" />
    <activity android:name="com.gabriele.tesina.Dolci" />
    <activity android:name="com.gabriele.tesina.Pizze" />
    <activity android:name="com.gabriele.tesina.Bevande" />
    <activity
        android:name="com.gabriele.tesina.AggiungiProdotto"
        android:label="Aggiungi Prodotto" >
    </activity>
</application>

logcat的:

03-09 14:43:09.347: W/Trace(771): Unexpected value from nativeGetEnabledTags: 0
03-09 14:43:09.737: W/System.err(771): org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
03-09 14:43:09.737: W/System.err(771):  at org.json.JSON.typeMismatch(JSON.java:111)
03-09 14:43:09.737: W/System.err(771):  at org.json.JSONObject.<init>(JSONObject.java:158)
03-09 14:43:09.747: W/System.err(771):  at org.json.JSONObject.<init>(JSONObject.java:171)
03-09 14:43:09.747: W/System.err(771):  at com.gabriele.tesina.AggiungiProdotto$AggiungoOrdinazione.doInBackground(AggiungiProdotto.java:113)
03-09 14:43:09.758: W/System.err(771):  at com.gabriele.tesina.AggiungiProdotto$AggiungoOrdinazione.doInBackground(AggiungiProdotto.java:1)
03-09 14:43:09.758: W/System.err(771):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-09 14:43:09.767: W/System.err(771):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-09 14:43:09.767: W/System.err(771):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-09 14:43:09.777: W/System.err(771):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-09 14:43:09.777: W/System.err(771):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-09 14:43:09.777: W/System.err(771):  at java.lang.Thread.run(Thread.java:856)

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我的清单中没有看到任何互联网许可。如果您希望它能够连接,您需要明确授予应用程序互联网访问权限。

将此添加到您的清单:

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

Source

答案 1 :(得分:0)

  

java.lang.String类型的DOCTYPE无法转换为JSONObject

您需要亲自检查请求格式以及服务器为何不发送有效JSON。

调试您的应用程序以检查来自服务器的响应。

检查JSON是否有效。

使用JSON Lint.