0

I'm trying to make a connection with my android app mysql.

I have read that it is a webservice.

I am trying to send two post variable to a php file in the url to keep this information in a mysql database.

The problem is that it does not send anything.

I'm starting aprogramar in android and for that I appreciated his friendly and helps to learn and solve the incoveniete.

I appreciate all your comments and help.

this is my class java:

    package com.example.prueba;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;




import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


public class EnviarVariables extends Activity {



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main); // aqui decimos que esta clase manipula los objetos del activity_saludo.xml


        Button btnSend = (Button) findViewById(R.id.button1);
        btnSend.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


               new Insertar(EnviarVariables.this).execute();



            }
    });




    }

    private boolean insertar(){

        EditText etNombre = (EditText) findViewById(R.id.editText1);
        EditText etEmail = (EditText) findViewById(R.id.editText2);

        HttpClient httpclient; //envia la info almacenada en httppost al webservice
        List<NameValuePair> nameValuePairs;
        HttpPost httppost; // almacena los datos a enviar, por medio de HttpClient
        httpclient = new DefaultHttpClient();
        httppost = new HttpPost("http://launidad.co/pruebaAndroid/index.php"); //url del servidor donde enviamos los datos

        nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("nombre",etNombre.getText().toString().trim()));
        nameValuePairs.add(new BasicNameValuePair("email",etEmail.getText().toString().trim()));

        try {
               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
               httpclient.execute(httppost);
               return true;
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return false;
        }



        //AsyncTask para insertar Personas
        class Insertar extends AsyncTask<String,String,String>{

            private Activity context;

            Insertar(Activity context){
                this.context=context;
            }
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                if(insertar())
                    context.runOnUiThread(new Runnable(){
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub                          
                            Toast.makeText(context, "Persona insertada con éxito", Toast.LENGTH_LONG).show();


                        }                       
                    });
                else
                    context.runOnUiThread(new Runnable(){
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub                          
                            Toast.makeText(context, "Persona no insertada con éxito", Toast.LENGTH_LONG).show();
                        }                   
                    });
                  return null;
            }           



        }





}
  • 1
    First, log your exceptions instead of silently ignoring them to learn where the code is failing. Second, look up `NetworkOnMainThreadException`. – laalto Jul 06 '14 at 18:49

1 Answers1

0

Of course this will not work. First: you cannot execute any http request in UI thread. Here is the question that should make things clearer.

If you want to send/receive any data over http, please consider following sceanarios:

  1. Using AsyncTask,
  2. Using Service and dynamically udating UI with BroadcastReceiver/EventBus/ Otto,
  3. Running separate thread within your activity and using runOnUiThread (this approach is the least elegant but possible).

As laalto suggested, please log your exceptions and find out what they mean.

Community
  • 1
  • 1
dawid gdanski
  • 2,432
  • 3
  • 21
  • 29
  • Hi there. I used AsyncTask as you recommended and I've edited my code, as you can see above, but still can not upload anything .. that does not happen ... –  Jul 06 '14 at 21:08
  • You don't even check the HttpResponse status. HttpClient's execute method returns HttpResponse object. From HttpResponse object you can check whether the http status is with accordance to your expectations. Besides you are not using the AsyncTask properly. Please note that Asynctask is generic abstract class and the types you include as generic are not just for the sake of them. – dawid gdanski Jul 07 '14 at 19:39