2013-03-06 3 views
0

Я пытаюсь создать приложение, которое отправляет данные на удаленный db с использованием WAMP-сервера. Проблема, с которой я сталкиваюсь, - никто не появляется: данные не отправляются, и не отображаются ошибки logcat, также я не могу вставить Toast, чтобы увидеть, распространяется ли приложение на определенные части кода, потому что Eclipse показывает его как ошибку во время выполнения Режим.Android HttpPost не работает

Итак, вы код .java:

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"); 
     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, связанные с данным вставки в БД:

<?php 


// Dichiaro una array nel quale inserirò la risposta in JSON 
$response = array(); 

/* La funzione isset controlla se all'interno della variabile esiste un dato diverso da null. 
$_POST è una funzione che inserisce i dati passati attraverso un metodo POST alla variabile seguente. */ 

if (isset($_POST['Nome']) && isset($_POST['Tavolo'])) 
{ 

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

    // Includo la classe per la connessione al database 
    require_once __DIR__ . '/connessione_db.php'; 

    // Da file incluso posso istanziare un oggetto della clase 
    $db = new DB_CONNECT(); 

    // Query in mySQL Per creare una riga i cui campi hanno i valori passati dall'applicazione. 
    $result = mysql_query("INSERT INTO pizze(Nome, Tavolo) VALUES('$Nome', '$Tavolo')"); 

    // Controllo se la riga è stata inserita oppure no. 
    if ($result) 
    { 

     $response["Stato"] = 1; 
     $response["Messaggio"] = "Dati inseriti!"; 

     // echo in PHP che mi converte il risultato in JSON e la mette nella variabile response. 
     echo json_encode($response); 
    } 
    else 
    { 

     $response["success"] = 0; 
     $response["message"] = "Dati non inseriti!"; 

     // Converto anche qui. 
     echo json_encode($response); 
    } 
} else 
{ 
    $response["success"] = 0; 
    $response["message"] = "Campo richiesto mancante!"; 

    // Converto. 
    echo json_encode($response); 
} 
?> 

Можете ли вы помочь мне, что не так? Является ли способ, которым я делаю правильный, или я что-то упускаю? Спасибо.

+0

вывесить LogCat. –

+0

LogCat не содержит ошибок. – Eulante

+0

У вас есть разрешение на использование Интернета в файле манифеста? – Raghunandan

ответ

1

Maby этот кусок кода может помочь.

Получить

InputStream is = null; 
    String result = ""; 
    JSONObject jsonResult = null; 

    HttpGet httppost = new HttpGet(url);  
    HttpParams httpParams = new BasicHttpParams(); 
    int timeOutConnection = 5000; 
    HttpConnectionParams.setConnectionTimeout(httpParams, timeOutConnection); 
    int timeoutSocket = 5000; 
    HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); 
    HttpClient httpclient = new DefaultHttpClient(httpParams); 



    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); 

Сообщение

 InputStream is = null; 
    String result = ""; 
    JSONObject jsonResult = null; 

    HttpPost httppost = new HttpPost(url); 
    //httppost.addHeader("content-type", "application/json"); 
    //httppost.addHeader("User-Agent", userAgent); 
    HttpParams httpParams = new BasicHttpParams(); 

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


    httppost.setEntity(new UrlEncodedFormEntity(params)); 

    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); 

обновление

попробовать оборачивать код в этом

new Thread(new Runnable() { 
      @Override 
      public void run() { 
       //To change body of implemented methods use File | Settings | File Templates. 
      } 
     }).start(); 

но я настоятельно рекомендую научиться использовать Asynctask, это делает его намного проще и стабильнее. есть много хороших примеров в сети, как их использовать

используйте этот код для справки и внесите в него изменения. Я уверен, что это работает, потому что мы все время используем этот мир кода.

Редактировать

Ниже я написал очень простую деятельность с подклассом AsyncTask

public class AsyncTaskExample extends Activity { 

private String url; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    url = "http://google.com"; 

    new WebCall().execute(); 
} 

class WebCall extends AsyncTask<String, Void, String> { 

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

     InputStream is = null; 
     String result = ""; 
     JSONObject jsonResult = null; 

     HttpPost httppost = new HttpPost(url); 
     //httppost.addHeader("content-type", "application/json"); 
     //httppost.addHeader("User-Agent", userAgent); 
     HttpParams httpParams = new BasicHttpParams(); 

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


     httppost.setEntity(new UrlEncodedFormEntity(params)); 

     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); 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 
     // this method gets called when doInBackground is ready with processing. 

     // onPostExecute is also returend on the UIThread. and doInbackground is not. 
     // so you cant setText or something else what involves UI components in the doInbackground. 
    } 
} 

}

его до вас, чтобы сделать все остальное;)

Надежда это помогает,

Сердечные приветы

+0

Привет, спасибо за ответ, но у меня есть несколько вопросов: - Могу ли я реализовать этот пример без AsyncTask или они нужны? - Как я вижу, мне просто нужно вставить мой url и мой ArrayList, который вы назвали params, не так ли? – Eulante

+0

нет, вам это нужно сделать на основе резьбы/асинтеза. или вы получите networkOnMainThreadException или что-то вроде этого –

+0

Так что это правильно, как в примере, не так ли? Спасибо за терпение. – Eulante

0

Пожалуйста, используйте этот код

List<NameValuePair> Parametri = new ArrayList<NameValuePair>(2); 

мгновением

List<NameValuePair> Parametri = new ArrayList<NameValuePair>(); 

Благодарности

+0

2 ссылается на максимальный размер моего списка или на количество его элементов для каждого индекса? – Eulante