Buttons + Intents with multiple destinations

1

From an activity with data from one sensor and two buttons, one to show graphs and another to show its parameters.

Question :

How to do it so that it takes to the corresponding activity when a click is done on one of the buttons. It seems obvious, but we must bear in mind that the object that opens can be either "Barometer" or "TemperatureHuemdadDht22" and that until the activity "InsertObjeto.java" is opened, the activity does not know if you are going to open "Barómetro" or "Temperature & Huemdad".

How the APP works:

ActivityListObjects.java

From a list, when I click on one of its components, open that component on another screen and give me all the data of that component. These components are in an external MySql database and synchronized with an internal SQlite to later populate the list and table with the synchronized data. In the example shown there are two components, but they could be 100 or 50 ...

screen list "ActivityListObjects.java"

Activity "ActivityOnsercionObjetos.java"

When you click on one of the objects in the previous list the App takes you to another activity that shows you the general data of that particular object and two buttons. If you click on one of them

a) Button = It takes you to a graph with the data of said object ("GraficaTemperaturaHuemdad.java" or "GraficaBarometro.java")

b) Button = It takes you to a table that is filled with the data of that Object ("Barometer.java" or "ResultHemperatureHumidityDht22.java".

** Note: An Object can have the same idObject as another, differentiated by its name not by its IdObject, since the IdObject describes the identifier of a motherboard that houses several sensors. *

Barometer

Activity "ActivityInsercionObjetos.java"

TemperatureHumidityDht22

When clicking on the "sensor data access" button, the app should take the data corresponding to the sensor shown, which may well be:

a) Barometro.java

b) TemperatureHumidityDht22.java

Code:

@TargetApi(Build.VERSION_CODES.M)

public class ActividadInsercionObjeto extends AppCompatActivity
    implements LoaderManager.LoaderCallbacks<Cursor>, View.OnClickListener {
// Referencias UI
private TextView campodescripcionNombre;
private TextView campoMarca;
private TextView campoModelo;
private TextView campoCorreo;
private TextView campoIdObjeto;
private Button accesodata;
private Button accesotabla;
public final static String EXTRA_ID = "idObjeto";
public EditText IdentidadObjeto;


// Clave del uri del objeto como extra
public static final String URI_OBJETO = "extra.uriObjeto";

private Uri uriObjeto;

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


    // Encontrar Referencias UI
    campodescripcionNombre = (TextView) findViewById(R.id.campo_descripcion_nombre);
    campoMarca = (TextView) findViewById(R.id.campo_marca);
    campoModelo = (TextView) findViewById(R.id.campo_modelo);
    campoCorreo = (TextView) findViewById(R.id.campo_correo);
    campoIdObjeto = (TextView) findViewById(R.id.campo_idObjeto);



    accesodata = (Button) findViewById(R.id.accesodata);
    accesodata.setOnClickListener(this);
    accesotabla = (Button) findViewById(R.id.accesotabla);
    accesotabla.setOnClickListener(this);

    // Determinar si es detalle
    String uri = getIntent().getStringExtra(URI_OBJETO);
    if (uri != null) {
        setTitle(R.string.titulo_actividad_editar_objeto);
        uriObjeto = Uri.parse(uri);
        getSupportLoaderManager().restartLoader(1, null, this);
    }



}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_insercion_objeto, menu);

    // Verificación de visibilidad acción eliminar
    if (uriObjeto != null) {
        menu.findItem(R.id.accion_eliminar).setVisible(true);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.accion_confirmar:
            insertar();
            break;
        case R.id.accion_eliminar:
            eliminar();
            break;
    }
    return super.onOptionsItemSelected(item);
}


private void insertar() {

    // Extraer datos de UI
    String descripcionNombre = campodescripcionNombre.getText().toString();
    String marca = campoMarca.getText().toString();
    String modelo = campoModelo.getText().toString();
    String correo = campoCorreo.getText().toString();
    String IdentidadObjeto = campoIdObjeto.getText().toString();



    // Validaciones y pruebas de cordura
    if (!esNombreValido(descripcionNombre)) {
        TextInputLayout mascaraCampoNombre = (TextInputLayout)findViewById(R.id.mascara_campo_nombre);

        // esta linea la he añadido, si da fallo eliminar. Sujerida por corrector
        assert mascaraCampoNombre != null;
        // esta linea la he añadido, si da fallo eliminar. Sujerida por corrector fin
        mascaraCampoNombre.setError("este campo no puede quedar vacio");
    } else {

        ContentValues valores = new ContentValues();

        // Verificación: ¿Es necesario generar un id?
        if (uriObjeto == null) {
            valores.put(Objetos.ID_OBJETO, Objetos.generarIdObjeto());
        }
        valores.put(Objetos.DESCRIPCION_NOMBRE, descripcionNombre);
        valores.put(Objetos.MARCA_MARCA, marca);
        valores.put(Objetos.MODELO, modelo);
        valores.put(Objetos.CORREO, correo);
        valores.put(Objetos.VERSION, UTiempo.obtenerTiempo());

        // Iniciar inserción|actualización
        new TareaAnadirObjeto(getContentResolver(), valores).execute(uriObjeto);



        finish();
    }
}

private boolean esNombreValido(String nombre) {
    return !TextUtils.isEmpty(nombre);
}

private void eliminar() {
    if (uriObjeto != null) {
        // Iniciar eliminación
        new TareaEliminarObjeto(getContentResolver()).execute(uriObjeto);
        finish();
    }
}


private void poblarViews(Cursor data) {
    if (!data.moveToNext()) {
        return;
    }

    // Asignar valores a UI
    campodescripcionNombre.setText(UConsultas.obtenerString(data, Objetos.DESCRIPCION_NOMBRE));
    campoMarca.setText(UConsultas.obtenerString(data, Objetos.MARCA_MARCA));
    campoModelo.setText(UConsultas.obtenerString(data, Objetos.MODELO));
    campoCorreo.setText(UConsultas.obtenerString(data, Objetos.CORREO));
    campoIdObjeto.setText(UConsultas.obtenerString(data, Objetos.ID_OBJETO));

}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this, uriObjeto, null, null, null, null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    poblarViews(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
}



   // @Override
   public void onClick (View v) {


           if (v == accesotabla) {

               Intent i = new Intent(ActividadInsercionObjeto.this, GraficaHumedadTemperatura.class);

               i.putExtra("IdentidadEnviada", (Serializable) campoIdObjeto.getText().toString());
               startActivity(i);

           }

       if (v == accesodata) {

           Intent i = new Intent(ActividadInsercionObjeto.this, **DEPENDEQUESENSORSEHIZOELCLIC.class**);
               i.putExtra("IdentidadEnviada", (Serializable) campoIdObjeto.getText().toString());
               startActivity(i);

       }
   }


static class TareaAnadirObjeto extends AsyncTask<Uri, Void, Void> {
    private final ContentResolver resolver;
    private final ContentValues valores;

    public TareaAnadirObjeto(ContentResolver resolver, ContentValues valores) {
        this.resolver = resolver;
        this.valores = valores;
    }

    @Override
    protected Void doInBackground(Uri... args) {
        Uri uri = args[0];
        if (null != uri) {
            /*
            Verificación: Si el cobjeto que se va a actualizar aún no ha sido sincronizado,
            es decir su columna 'insertado' = 1, entonces la columna 'modificado' no debe ser
            alterada
             */
            Cursor c = resolver.query(uri, new String[]{Objetos.INSERTADO}, null, null, null);

            if (c != null && c.moveToNext()) {

                // Verificación de sincronización
                if (UConsultas.obtenerInt(c, Objetos.INSERTADO) == 0) {
                    valores.put(Objetos.MODIFICADO, 1);
                }

                valores.put(Objetos.VERSION, UTiempo.obtenerTiempo());
                resolver.update(uri, valores, null, null);
            }

        } else {
            resolver.insert(Objetos.URI_CONTENIDO, valores);
        }
        return null;
    }

}

static class TareaEliminarObjeto extends AsyncTask<Uri, Void, Void> {
    private final ContentResolver resolver;

    public TareaEliminarObjeto(ContentResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    protected Void doInBackground(Uri... args) {

        /*
        Verificación: Si el registro no ha sido sincronizado aún, entonces puede eliminarse
        directamente. De lo contrario se marca como 'eliminado' = 1
         */
        Cursor c = resolver.query(args[0], new String[]{Objetos.INSERTADO}
                , null, null, null);

        int insertado;

        if (c != null && c.moveToNext()) {
            insertado = UConsultas.obtenerInt(c, Objetos.INSERTADO);
        } else {
            return null;
        }

        if (insertado == 1) {
            resolver.delete(args[0], null, null);
        } else if (insertado == 0) {
            ContentValues valores = new ContentValues();
            valores.put(Objetos.ELIMINADO, 1);
            resolver.update(args[0], valores, null, null);
        }

        return null;
    }
}

}

    
asked by Oscar C. 28.08.2016 в 18:10
source

1 answer

1

Response found by: cricket_007

 if (v == accesodata) {

           String nombre = campodescripcionNombre.getText().toString();
           if (nombre.equals("Barometro")) {

               Intent i = new Intent(ActividadInsercionObjeto.this, Barometro.class);
               i.putExtra("IdentidadEnviada", (Serializable) campoIdObjeto.getText().toString());
               startActivity(i);

           } else {
               Intent i = new Intent(ActividadInsercionObjeto.this, TemperaturaHumedadDht22.class);
               i.putExtra("IdentidadEnviada", (Serializable) campoIdObjeto.getText().toString());
               startActivity(i);
           }
       }
   }

It could also be:

if (v == accesodata) {
Class c = null;
String nombre = campodescripcionNombre.getText().toString();
if (nombre.equals("Barometro") { // TODO: figure out what you should check 
    c = Barometro.class;
} else {
    c = TemperaturaHuemdadDht22.class;
} 
Intent i = new Intent(ActividadInsercionObjeto.this, c);
i.putExtra("IdentidadEnviada", (Serializable) campoIdObjeto.getText().toString());
startActivity(i);
    
answered by 28.08.2016 / 21:08
source