0

WAMPサーバーを使用してリモートデータベースにデータを送信するアプリケーションを作成しようとしています。私が直面している問題は、誰も表示されないことです。データが送信されず、logcatエラーが表示されません。また、Eclipseが実行時にエラーとして表示するため、アプリケーションがコードの特定の部分に入るかどうかを確認するためにToastを挿入できません。モード。

したがって、ここに.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()
{

}

}

次に、dbへのデータの挿入に関連する.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);
}
?>

何が悪いのか手伝ってもらえますか?私のやり方は正しいですか、それとも何かが足りませんか?ありがとうございました。

4

2 に答える 2

1

このコードのチャンクが役立つかもしれません。

得る

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.
    }
}

}

残りはあなた次第です;)

それが役に立てば幸い、

敬具

于 2013-03-06T17:47:22.173 に答える
0

このコードを使用してください

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

の瞬間

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

ありがとう

于 2013-03-06T17:54:01.800 に答える