update data in a remote database android studio

0

I'm trying to insert data into a remote mysql database .. I'm stuck .. I've looked for examples but nothing like that

This is my java code

 import android.app.ProgressDialog;
 import android.content.Context;
 import android.content.Intent;
 import android.os.AsyncTask;
 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.Snackbar;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.view.View;
 import android.view.WindowManager;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.RadioButton;
 import android.widget.RadioGroup;
 import android.widget.TextView;

 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;

 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.net.URL;
 import java.net.URLConnection;

public class Modificar extends AppCompatActivity {
String status;
ProgressDialog pdialog = null;
Context context = null;
TextView tvnombre,
        tvfolio,
        tvasunto,
        tvfecha,
        tvdireccion,
        tvtelefono,
        tvlugar,
        tvestado;

EditText txobservaciones;
Button actualizar, borrar, turnar;

RadioButton activo,pendiente,concluido,noprocede;
RadioGroup grupo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_modificar);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    Intent intent = getIntent();
    String nombre = intent.getStringExtra("nombre");
    String folio = intent.getStringExtra("folio");
    String asunto = intent.getStringExtra("asunto");
    String fecha = intent.getStringExtra("fecha");
    String direccion = intent.getStringExtra("direccion");
    String telefono = intent.getStringExtra("telefono");
    String lugar = intent.getStringExtra("lugar");
    String estado = intent.getStringExtra("estado");
    String observaciones = intent.getStringExtra("observaciones");

    tvnombre = (TextView)findViewById(R.id.tvnombre);
    tvasunto = (TextView)findViewById(R.id.tvasunto);
    tvfolio = (TextView)findViewById(R.id.tvfolio);
    tvfecha = (TextView)findViewById(R.id.tvfecha);
    tvdireccion = (TextView)findViewById(R.id.tvdireccion);
    tvestado = (TextView)findViewById(R.id.tvestado);
    tvtelefono = (TextView)findViewById(R.id.tvtelefono);
    tvlugar = (TextView)findViewById(R.id.tvlugar);
    txobservaciones = (EditText)findViewById(R.id.txobservaciones);
    actualizar = (Button)findViewById(R.id.btnmodificar);
    borrar = (Button)findViewById(R.id.btnborrar);
    turnar = (Button)findViewById(R.id.btnturnar);
    activo = (RadioButton)findViewById(R.id.radioActivo);
    pendiente = (RadioButton)findViewById(R.id.radioPendiente);
    concluido = (RadioButton)findViewById(R.id.radioConcluido);
    noprocede = (RadioButton)findViewById(R.id.radioNoprocede);
    grupo = (RadioGroup)findViewById(R.id.radioGroup);

    tvnombre.setText(nombre);
    tvasunto.setText(asunto);
    tvfolio.setText("Folio: "+folio);
    tvfecha.setText(fecha);
    tvdireccion.setText(direccion);
    tvtelefono.setText(telefono);
    tvlugar.setText(lugar);
    tvestado.setText(estado);
    txobservaciones.setText(observaciones);

    // decicion para comprobar el status inicial del radiobutton
    status = tvestado.getText().toString();
    if (status.equals("Activo")){
        activo.setChecked(true);
    }else if (status.equals("Pendiente")){
        pendiente.setChecked(true);
    }else if (status.equals("Concluido")){
        concluido.setChecked(true);
    }else if (status.equals("No Procede")){
        noprocede.setChecked(true);
    }

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    borrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            txobservaciones.setText("");
        }
    });
    actualizar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            String folio, estado, observaciones;

            folio = tvfolio.getText().toString();
            estado = tvestado.getText().toString();
            observaciones = txobservaciones.getText().toString();
        }
    });

    turnar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
}

class ReadJSON extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        return readURL(params[0]);
    }
    @Override
    protected void onPostExecute(String content) {

        pdialog.dismiss();
        try {



            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

private static String readURL(String theUrl) {
    StringBuilder content = new StringBuilder();
    try {
        // create a url object
        URL url = new URL(theUrl);
        // create a urlconnection object
        URLConnection urlConnection = url.openConnection();
        // wrap the urlconnection in a bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        // read from the urlconnection via the bufferedreader
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}

}

This is my json code

   <?php

  $estado = $_GET["estado"];
  $folio = $_GET["folio"];
  $observaciones = $_GET["observaciones"];

  $link =      mysqli_connect("xxxxxxxx","xxxxxxxxx","xxxxxxxx","xxxxxxxx")  or die("Error en la conexion" . mysqli_error($link));

   $resultado = mysqli_query($link,"UPDATE solicitudes 
                                SET folio = '$folio',                                                                           
                                    estado = '$status',
                                    observaciones = '$observaciones'                        
                                WHERE folio = '$folio' ORDER BY folio  DESC");

    ?>
    
asked by Sharly Infinitywars 14.03.2017 в 20:57
source

1 answer

1

I WILL GIVE YOU AN EXAMPLE OF A LOGIN SESSION THAT I HAVE MADE THEMSELVES.
1st The class that will allow you to send data to a web server (whatever it may be). I do not remember where I found it but I adapted it to my needs.

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class clsAndroidPHP extends AsyncTask<String, Void, String> {
    public static final int ESPERA_CONEXION=10000;
    public static final int ESPERA_LECTURA=15000;
    private Context ContextoClase;
    HttpURLConnection ConexionHTTP;
    URL DireccionURL = null;
    int nTotDatEnvio;
    public clsAndroidPHP(Context ContextoConst) {
        this.ContextoClase = ContextoConst;
    }
    private OnTaskExecutionFinished _task_finished_event;

    public interface OnTaskExecutionFinished    {
        public void OnTaskFihishedEvent(String Result);
    }

    public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)   {
        if(_event != null)    {
            this._task_finished_event = _event;
        }
    }

    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... arg0) {
        nTotDatEnvio = arg0.length;
        /*Intentar crear URL de servidor*/
        try {
            DireccionURL = new URL(arg0[0]);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "ERROR-URL";
        }
        /*Intentar establecer conexión y enviar datos al servidor web*/
        try {
            // Configurar conexión mediante HttpURLConnection
            ConexionHTTP = (HttpURLConnection)DireccionURL.openConnection();
            ConexionHTTP.setReadTimeout(ESPERA_LECTURA);
            ConexionHTTP.setConnectTimeout(ESPERA_CONEXION);
            ConexionHTTP.setRequestMethod("POST");
            // activar envio (setDoInput) y recepción (setDoOutput)
            ConexionHTTP.setDoInput(true);
            ConexionHTTP.setDoOutput(true);
            // Añadir parámetros a URL
            Uri.Builder builder = new Uri.Builder();
            for (int nDatEnvio=1; nDatEnvio<nTotDatEnvio;nDatEnvio++){
                builder.appendQueryParameter("DATO" + String.valueOf(nDatEnvio), arg0[nDatEnvio]);
            }
            String Peticion = builder.build().getEncodedQuery();
            // abrir conexion para enviar datos
            OutputStream Salida = ConexionHTTP.getOutputStream();
            BufferedWriter Escribir = new BufferedWriter(new OutputStreamWriter(Salida, "UTF-8"));
            Escribir.write(Peticion);
            Escribir.flush();
            Escribir.close();
            Salida.close();
            ConexionHTTP.connect();
        } catch (IOException e1) {
            e1.printStackTrace();
            return "ERROR-CON";
        }
        /*Intentar leer datos del servidor*/
        try {
            int Respuesta = ConexionHTTP.getResponseCode();
            // Si la conexión ha sido establecida correctamente
            if (Respuesta == HttpURLConnection.HTTP_OK) {
                // Leer datos del servidor
                InputStream Entrada = ConexionHTTP.getInputStream();
                BufferedReader Leer = new BufferedReader(new InputStreamReader(Entrada));
                StringBuilder Resultado = new StringBuilder();
                String Linea;
                while ((Linea = Leer.readLine()) != null) {
                    Resultado.append(Linea);
                }
                // Pasar datos al método onPostExecute
                return(Resultado.toString());
            }else{
                return ("ERROR-RESP");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "ERROR-RESP2";
        } finally {
            ConexionHTTP.disconnect();
        }
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if(this._task_finished_event != null)        {
            this._task_finished_event.OnTaskFihishedEvent(result);
        }  else     {
            //
        }

    }
}

2nd: How to use it:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONException;
import org.json.JSONObject;
public class fraSesion extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.lytsesion, container, false);
        Button xSesion = (Button) view.findViewById(R.id.btnSesion);
        final EditText xUsu = (EditText) view.findViewById(R.id.txtUsuario);
        final EditText xClave = (EditText) view.findViewById(R.id.txtClave);

        xSesion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String sUsu, sClave, sURL;
                sUsu = xUsu.getText().toString();
                sClave = xClave.getText().toString();
                sURL = "http://www.sitio.com/sesion.php";
                //////////////////////////////////////////////////////////////////////////////////////
                //IMPLEMENTANDO LA CLASE PARA ENVIAR DATOS A UN SERVIDOR WEB
                //////////////////////////////////////////////////////////////////////////////////////
                //aqui uso getActivity() porque lo estoy llamando desde un fragment
                clsAndroidPHP cHTTP = new clsAndroidPHP(getActivity());
                //aqui envio la URL, el Usuario y su clave (contraseña)
                cHTTP.execute(sURL, sUsu, sClave);

                //////////////////////////////////////////////////////////////////////////////////////
                //CAPTURANDO RESULTADOS DEVUELTOS
                //////////////////////////////////////////////////////////////////////////////////////
                /*evento que indica que Asyn Task a finalizado y devuelto los resultados*/
                cHTTP.setOnTaskFinishedEvent(new clsAndroidPHP.OnTaskExecutionFinished() {
                    @Override
                    public void OnTaskFihishedEvent(String result) {
                        String CadenaJSON = result;
                        if (CadenaJSON != null) {
                            if (CadenaJSON.equals("ERROR-URL") || CadenaJSON.equals("ERROR-CON") || CadenaJSON.equals("ERROR-RESP") || CadenaJSON.equals("ERROR-RESP2")) {
                                //Toast para mostrar un mensaje de error por conexión
                            }else {
                                try {
                                    /*aqui convierto el string JSON de PHP en objetos JSON para parsearlo
                                    y leer sus valores*/
                                    JSONObject ObjetoJSON = new JSONObject(CadenaJSON);
                                    String sMen1 = ObjetoJSON.getString("MEN1");
                                    String sMen2 = ObjetoJSON.getString("MEN2");
                                    /*aquí consulto el valor de cada item JSON*/
                                    if (sMen1.equals("ERROR")) {
                                        //toast si usuario no puede iniciar sesion
                                    }else if (sMen1.equals("CORRECTO")) {
                                        // codigo si el usuario si puede iniciar sesión, que puede 
                                        // llamar a un fragment o un activity
                                        // en la variable sMen2 se almacenará el nombre del usuario encontrado
                                        // el cual puedes enviarlo con bundle
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    //Toast indicacndo que JSON es erróneo
                                }
                            }
                        } else {
                            //Toast indicando que JSON no se puede leer
                        }
                    }
                });
            }
        });
       return view;
    }
 }  
  

The data that is sent to the class is an array, so the first parameter (pos 0) must always be the URL, from the second parameter (pos > = 1) it can be anything, they can be be as many as you want

     

At least you must send the URL and at least one data, if you have nothing to send apart from the URL, this can be an empty String, otherwise the shipping class will fail because it did not receive a parameter after the URL. Ex.

            cHTTP.execute(sURL, "");  

3rd: The PHP part:

<?php
    if(isset($_POST['DATO1']) and isset($_POST['DATO2'])){
        $sUsuar = $_POST['DATO1'];
        $sClave = $_POST['DATO2'];

        /*consulta SQL para verificiar login y su respectiva 
        verificion bla bla bla*/

        /*si el login es correcto envio un JSON de CORRECTO y los datos del usuario en la base de datos*/
        echo "{'MEN1':'CORRECTO','MEN2':'$NOMBRE_USUARIO'}";
        /*si es incorrecto, envio un JSON de Error*/
        echo "{'MEN1':'ERROR','MEN2':'NADA'}";
    }
?>  

I hope it serves you, it's a very complete example.

    
answered by 15.03.2017 / 19:03
source