I'm attempting to create an application which send data to a remote db using WAMP server. The problem I'm facing is no one appears: no data are sent and no logcat errors are shown, also I can't insert a Toast to see if the application goes into specific parts of code because Eclipse shows it as an errore in runtime mode.
So, here you are the .java code:
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()
{
}
}
Then here you are the .PHP code related to the insert data into the db:
<?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);
}
?>
Can you help me what is wrong? Is the way im doing correct or am I missing something? Thank you.
Maby this chunk of code can help.
Get
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);
Post
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);
update
try wrapping your code in this
new Thread(new Runnable() {
@Override
public void run() {
//To change body of implemented methods use File | Settings | File Templates.
}
}).start();
but i higly recommend to learn to use the Asynctask, it makes it a lot easier and more stable. the are lots of good examples on the net of how to use them
use this code for reference and modify it on your needs. I am sure that this works cause we use this peace of code all the time.
Edit
Below I wrote a very simple activity with a subclass of 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.
}
}
}
its up to you to do the rest ;)
Hope it helps,
Kind regards
Please Use this code
List<NameValuePair> Parametri = new ArrayList<NameValuePair>(2);
instant of
List<NameValuePair> Parametri = new ArrayList<NameValuePair>();
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.