user2634633
user2634633

Reputation: 529

Inserting data into MySQL using http-post and AsyncTask doesn't work

I am making an app that needs to post some data in MySQL database. The code doesn't show any errors, but no data is sent. My php file and HttpPost seem to work fine - I tried changing the php file so that it already included the data and then it worked. Here's my php:

<?php

$username = "user";
$password = "password";
$hostname = "mysql.xxx.com"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
  or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";


//select a database to work with
$selected = mysql_select_db("myapp_xxx_com",$dbhandle) 
  or die("Could not select examples");


//retrieve the data
$street = $_POST['Street'];
$house = $_POST['House'];
$city = $_POST['City'];
$comment = $_POST['Comment'];

mysql_query ("INSERT INTO Address (Street, Number, City, Comment, TimeOrdered) VALUES('$street', '$house, '$city', '$comment', NOW())");

mysql_close($dbhandle);

?>

And here's my java code:

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class OrderSummary extends Activity implements OnClickListener {

    private EditText editStreetText, editNumberText, editCityText, editCommentText;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_summary);

        editStreetText = (EditText) findViewById(R.id.summary_street);
        editNumberText = (EditText) findViewById(R.id.summary_house);
        editCityText = (EditText) findViewById(R.id.summary_city);
        editCommentText = (EditText) findViewById(R.id.summary_comment);
        button = (Button)findViewById(R.id.button_post_data);
        button.setOnClickListener(this);


    @Override
    public void onClick(View v) {

        String streetValue = editStreetText.getText().toString();
        String numberValue = editNumberText.getText().toString();
        String cityValue = editCityText.getText().toString();
        String commentValue = editCommentText.getText().toString();
        new SummaryAsyncTask().execute(streetValue, numberValue, cityValue, commentValue);

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    public void postData(String street, String number, String city, String comment)
    {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://xxxxxxx.com/postdata.php");

        try{
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("Street", street));
            nameValuePairs.add(new BasicNameValuePair("House", number));
            nameValuePairs.add(new BasicNameValuePair("City", city));
            nameValuePairs.add(new BasicNameValuePair("Comment", comment));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error:  "+e.toString());
        } 

    }

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

        protected Void doInBackground(String... params){
            postData(params[0], params[1], params[2], params[3]);
            return null;
        }
    }

    }
}

I based the code on this tutorial http://mobiledevtuts.com/android/android-http-with-asynctask-example/ . I hope someone can help me with this.

Upvotes: 1

Views: 8782

Answers (2)

Issac Balaji
Issac Balaji

Reputation: 1441

public class RefreshChildren extends AsyncTask{

WebService service;
Helper helper;

RefreshChildren(){
    service =new WebService();
    helper =new Helper(null);
}

@Override
protected String doInBackground(String... params) {
    refreshChildren();
    return null;
}   

private void refreshChildren() {
    Log.d("Refresh", "children started");
    List<ChildrenInstallBeen> childrenList=new ArrayList<ChildrenInstallBeen>();
    childrenList=service.getChildrenListRefresh();
    Iterator<ChildrenInstallBeen> iterator=childrenList.iterator();
    while (iterator.hasNext()) {
        ChildrenInstallBeen been = (ChildrenInstallBeen) iterator
                .next();
        Log.d("refresh children : ", ""+been.getFirst_name());

    }

}

}

Upvotes: 0

Carlo Espino
Carlo Espino

Reputation: 1384

You got an error in the PHP: '$house must be '$house'

Java code tested and working I just changed it a little bit

import android.os.Bundle;
import android.app.Activity;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class OrderSummary extends Activity {

    String streetValue;
    String numberValue;
    String cityValue;
    String commentValue;

    private EditText editStreetText, editNumberText, editCityText, editCommentText;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_summary);

        editStreetText = (EditText) findViewById(R.id.summary_street);
        editNumberText = (EditText) findViewById(R.id.summary_house);
        editCityText = (EditText) findViewById(R.id.summary_city);
        editCommentText = (EditText) findViewById(R.id.summary_comment);

        button = (Button) findViewById(R.id.button_post_data);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                streetValue = editStreetText.getText().toString();
                numberValue = editNumberText.getText().toString();
                cityValue = editCityText.getText().toString();
                commentValue = editCommentText.getText().toString();
                new SummaryAsyncTask().execute((Void) null);
            }
        }); 
    }

    class SummaryAsyncTask extends AsyncTask<Void, Void, Boolean> {

        private void postData(String street, String number, String city,
                String comment) {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://xxxxxxx.com/postdata.php");

            try {
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                nameValuePairs.add(new BasicNameValuePair("Street", street));
                nameValuePairs.add(new BasicNameValuePair("House", number));
                nameValuePairs.add(new BasicNameValuePair("City", city));
                nameValuePairs.add(new BasicNameValuePair("Comment", comment));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
            }
            catch(Exception e)
            {
                Log.e("log_tag", "Error:  "+e.toString());
            }
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            postData(streetValue, numberValue, cityValue, commentValue);
            return null;
        }
    }
}

Do not forget the Internet permission on android manifest

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

You can put the permission after <uses-sdk /> tag

Upvotes: 3

Related Questions