简体   繁体   中英

One activity 2 buttons which can go different activities

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

Question:

When you click on one of the buttons it must go its activity. It seems obvious, but take in mind that the object can be "barometer" or "TemperaturaHuemdadDht22".

From a list, when I click on one of its components, the component opens another screen and gives me all data from that component. These components are in an external database MySql and is synchronized with an internal SQlite then populate with data synchronized list and table. In the example shown there are two components, but may be 100 or 50 ...

Once you clic to data sensor button then you go to another activity , or Barometro.java or TemperaturaHumedadDht22.java

Pls check the Scheme: Scheme

Specially in code check public void onClick (View v) method

if (v == accesodata) {

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

Code :

@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, **DEPENEDSONWHICHBUTTONYOUCLICK.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;
    }
}

}

I don't know how you want to handle this

it is determinated by the name of the sensor showed in "ActividadInsertarObjeto.java"

But you seem to understand you need to check that value, so just do it

if (v == accesodata) {
    Class c = null;
    if (someCondition) { // 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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM