edittext comparison: Prevent duplicate date and time

Asked

Viewed 111 times

0

//-------CLASSE QUE FAZ INSERT,ALTER,DELETE ATRAVES DE DADOSDADOS PELA CLASSE AGENDARF(CLASSE COM OS EDTTEXTS E SPINNERS)

package com.example.userlocal.oficinadocabelo.Agenda;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import com.example.userlocal.oficinadocabelo.banco.banco;

/**
* Created by danrock on 19/11/2016.
*/
public class ControlarAgedamento {

private SQLiteDatabase db;
private banco banco;

public ControlarAgedamento(Context context){banco = new banco(context);
}

public String insereAgenda(String nome, String dia, String horario, String corte, String valor){
    ContentValues valores;
    long resultado;

    db = banco.getWritableDatabase();
    valores = new ContentValues();
    valores.put(banco.NOMECLIAGE, nome);
    valores.put(banco.DATA, dia );
    valores.put(banco.HORA, horario);
    valores.put(banco.SERVICO,corte );
    valores.put(banco.VALOR,valor );
    validar(dia,horario);
    resultado = db.insert(banco.TABELAAGE, null, valores);
    db.close();

    if (resultado ==-1)
        return "Erro ao inserir registro";
    else
        return "Registro Inserido com sucesso";

}

public Cursor carregaDados(){
    Cursor cursor;
    String[] campos =  {banco.IDAGE,banco.NOMECLIAGE,banco.DATA,banco.HORA,banco.SERVICO,banco.VALOR};
    db = banco.getReadableDatabase();
    cursor = db.query(banco.TABELAAGE, campos, null, null, null, null, null, null);

    if(cursor!=null){
        cursor.moveToFirst();
    }
    db.close();
    return cursor;
}

public Cursor carregaDadoById(int id){
    Cursor cursor;
    String[] campos =  {banco.IDAGE,banco.NOMECLIAGE,banco.DATA,banco.HORA,banco.SERVICO,banco.VALOR};
    String where = banco.IDAGE + "=" + id;
    db = banco.getReadableDatabase();
    cursor = db.query(banco.TABELAAGE,campos,where, null, null, null, null, null);

    if(cursor!=null){
        cursor.moveToFirst();
    }
    db.close();
    return cursor;
}

public void alteraHorario(int id, String nome, String telefone, boolean email, String idade, String valor){
    ContentValues valores;
    String where;

    db = banco.getWritableDatabase();

    where = banco.IDAGE + "=" + id;

    valores = new ContentValues();
    valores.put(banco.NOMECLIAGE, nome);
    valores.put(banco.DATA, telefone);
    valores.put(banco.HORA, email);
    valores.put(banco.SERVICO, idade);
    valores.put(banco.VALOR, valor);


    db.update(banco.TABELAAGE,valores,where,null);
    db.close();
}
public void deletaRegistro(int id){
    String where = banco.IDAGE + "=" + id;
    db = banco.getReadableDatabase();
    db.delete(banco.TABELAAGE,where,null);
    db.close();
}

public  Integer validarData(final String DATA, final String HORA){

    SQLiteDatabase db = banco.getWritableDatabase();
    final Cursor cursor = db.query(banco.TABELAAGE, new String[]{"id"}, "DATA = ? AND HORA =?", new String[]{DATA,HORA}, null, null, null, null);
    //se nulo ou vazio não encontrou nenhum com a mesma data e hora, retorna -1
    if (null == cursor || !cursor.moveToFirst()) return -1;

    final Integer id = cursor.getInt(0);
    cursor.close();
    return id;
}

public void validar(String dia, String horario) {
    Integer idComDataEHora = validarData(dia, horario);
    if (idComDataEHora.equals(-1)) {
        // não exite nenhum registro
    } else {
        /// Se vc está editando, verifique se o id é igual ao que está editando!

    }

}
}




//////Classe que cria o banco


package com.example.userlocal.oficinadocabelo.banco;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class banco extends SQLiteOpenHelper {
    public static final String NOME_BANCOCLI = "bancocli";
    public static final String TABELACLI = "cliente";
    public static final int VERSAOCLI = 1;
    public static final String IDCLI = "_id";
    public static final String IMGCLI = "img";
    public static final String NOMECLI = "nome";
    public static final String TELEFONECLI = "telefone";
    public static final String CELULARCLI = "celular";
    public static final String EMAILCLI = "email";
    public static final String SEXOCLI = "sexo";
    public static final String CODCLI = "codigo";
    //---------------------------------------------------------
    public static final String TABELAFUN = "funcionario";
    public static final String IDFUN = "_id";
    public static final String IMGFUN = "imagem";
    public static final String NOMEFUN = "nome";
    public static final String TELEFONEFUN = "telefone";
    public static final String CELULARFUN = "celular";
    public static final String CARGOFUN = "cargo";
    public static final String SALARIOFUN = "salario";
    public static final String SEXOFUN = "sexo";
//----------------------------------------------------------

    public static final String TABELAPRO = "produto";
    public static final String IDPRO = "_id";
    public static final String IMGPRO = "imagem";
    public static final String NOMEPRO = "nome";
    public static final String QUANTIDADEPRO = "quantidade";
    public static final String MARCAPRO = "marca";
    //---------------------------------------------------------
    public static final String TABELAAGE = "agenda";
    public static final String IDAGE = "_id";
    public static final String NOMECLIAGE = "nome";
    public static final String DATA = "dia";
    public static final String HORA = "hora";
    public static final String SERVICO = "corte";
    public static final String VALOR = "valor";


    public banco(Context context){
        super(context, NOME_BANCOCLI, null, VERSAOCLI);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE "+TABELACLI+"("
            +IDCLI+ " integer primary key autoincrement,"
            +IMGCLI+ " blob,"
            +NOMECLI+ " text not null,"
            +TELEFONECLI+ " text not null,"
            +CELULARCLI+ " text not null,"
            +EMAILCLI+ " text not null,"
            +SEXOCLI+ " text not null,"
            +CODCLI+ " text not null"
            +");";

                db.execSQL(sql);

            String sql2 = "CREATE TABLE "+TABELAFUN+"("
            +IDFUN+ " integer primary key autoincrement,"
            +IMGFUN+ " blob,"
            +NOMEFUN+ " text not null,"
            +TELEFONEFUN+ " text not null,"
            +CELULARFUN+ " text not null,"
            +SALARIOFUN+ " text not null,"
            +CARGOFUN+ " text not null,"
            +SEXOFUN+ " text not null"
            +");";

                db.execSQL(sql2);

            String sql3 ="CREATE TABLE "+TABELAPRO+"("
            +IDPRO+ " integer primary key autoincrement,"
            +IMGPRO+ " blob,"
            +NOMEPRO+ " text not null,"
            +MARCAPRO+ " text,"
            +QUANTIDADEPRO+ " text not null"
            +");";

                 db.execSQL(sql3);

            String sql4 ="CREATE TABLE "+TABELAAGE+"("
            +IDAGE+ " integer primary key autoincrement,"
            +NOMECLIAGE+ " text not null,"
            +DATA+ " text not null,"
            +HORA+ " text not null,"
            +SERVICO+ " text not null,"
                    +VALOR+ " text not null"
            +")";

                db.execSQL(sql4);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + TABELACLI);
        onCreate(db);
        db.execSQL("DROP TABLE IF EXISTS" + TABELAAGE);
        onCreate(db);
        db.execSQL("DROP TABLE IF EXISTS" + TABELAFUN);
        onCreate(db);
        db.execSQL("DROP TABLE IF EXISTS" + TABELAPRO);
        onCreate(db);
    }




}

////CLASSE AGENDARF


package com.example.userlocal.oficinadocabelo.Agenda;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

import com.example.userlocal.oficinadocabelo.R;
import com.example.userlocal.oficinadocabelo.TelaInicial;
import com.example.userlocal.oficinadocabelo.banco.banco;

public class AgendarF extends AppCompatActivity implements Button.OnClickListener {


private EditText Nome,Dia,Corte,valor;
private AlertDialog alerta;
private ImageButton data;
private ImageView btncadastrar,btnvoltar;
static final int DATE_DIALOG_ID = 0;
private String DataFinal;
private Spinner Hora;

private banco banco;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cadastrar_horario);
    data =(ImageButton) findViewById(R.id.imgdata);
    data.setOnClickListener(this);


    btncadastrar =(ImageView)findViewById(R.id.btnCadastrarHorarioSalvar);
    Nome =(EditText) findViewById(R.id.edtNome);
    Hora =(Spinner) findViewById(R.id.spinerhorario);
    Dia = (EditText) findViewById(R.id.txtData);
    Corte =(EditText) findViewById(R.id.edtCorte);
    data=(ImageButton) findViewById(R.id.imgdata);
    valor=(EditText) findViewById(R.id.edtValor);

    ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.spinnerhorario, android.R.layout.simple_spinner_item);
    Hora.setAdapter(adapter);

    btncadastrar.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            String spvalor = Hora.getSelectedItem().toString();
            if(Dia.getText().length() == 0 ||Hora.equals(null) ||Corte.getText().length() == 0){
                Toast.makeText(getApplicationContext(), "Nenhum campo pode estar vazio", Toast.LENGTH_LONG).show();
            }else {


               ControlarAgedamento ca = new ControlarAgedamento(getBaseContext());
                String nomeString = Nome.getText().toString();
                String diaString = Dia.getText().toString();
                String horaString = spvalor;
                String corteString = Corte.getText().toString();
                String valorString = valor.getText().toString();

                String resultado;

                resultado = ca.insereAgenda(nomeString, diaString, horaString, corteString, valorString );

                Intent i = new Intent(AgendarF.this, Agenda.class);
                startActivity(i);
                finish();
                Toast.makeText(getApplicationContext(), "Horario Marcado", Toast.LENGTH_LONG).show();
            }
        }
    });

}
@Override
protected Dialog onCreateDialog(int id) {
    Calendar calendario = Calendar.getInstance();

    int ano = calendario.get(Calendar.YEAR);
    int mes = calendario.get(Calendar.MONTH);
    int dia = calendario.get(Calendar.DAY_OF_MONTH);

    switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, ano, mes,
                    dia);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) {
        String data = String.valueOf(dayOfMonth) + " /"
                + String.valueOf(monthOfYear+1) + " /" + String.valueOf(year);
        Toast.makeText(AgendarF.this,
                "DATA = " + data, Toast.LENGTH_SHORT)
                .show();
        DataFinal= data;
        Dia.setText(DataFinal);
    }
};

@Override
public void onClick(View v) {
    if (v == data)
        showDialog(DATE_DIALOG_ID);
}
//////////////Acaba Calendario//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




}
  • You can put the error that occurs?

  • android.database.sqlite.Sqliteexception: no such column: id (code 1): while compiling: SELECT id FROM agenda WHERE DATA = ? AND HORA =?

  • at com.example.userlocal.oficinadocabelo.Agenda.ControlarAgedamento.validarData(Controlcontrol.java:100)

  • He couldn’t find the column id, because the table in the agenda table is _id change in the validator method to : new String[]{"_id"}

  • the error is gone but how do I prevent it from registering, to display a message "busy time" through a Toast for example

  • I will answer below! I will also change the name of the question to facilitate

Show 1 more comment

1 answer

0

Try the following:

public String insereAgenda(String nome, String dia, String horario, String corte, String valor){
    ContentValues valores;
    long resultado;


  Integer idComMesmoDataHora = validarData(dia, horario);

  // Se não for igual a -1, é porque já existe
  if (!idComMesmoDataHora.equals(-1)) {
    return "Já existe este horário cadastrado!";
   }

    db = banco.getWritableDatabase();
    valores = new ContentValues();
    valores.put(banco.NOMECLIAGE, nome);
    valores.put(banco.DATA, dia );
    valores.put(banco.HORA, horario);
    valores.put(banco.SERVICO,corte );
    valores.put(banco.VALOR,valor );
    validar(dia,horario);
    resultado = db.insert(banco.TABELAAGE, null, valores);
    db.close();

    if (resultado ==-1)
        return "Erro ao inserir registro";
    else
        return "Registro Inserido com sucesso";

}
  • Thanks worked, did not register but still displays the scheduled time message, have some way to display a Toast if the time is the same, I tried but n knew how because Toast has to be displayed in the Agendarf class and the verification method is in the Controlragenda class

  • you need to do the treatment: if(result.equals("Record Successfully Inserted")) , calls Activity, otherwise it shows Toast! If the answer was useful, mark as correct!

  • I don’t understand, because if I do this in the Controlagenda class I won’t be able to display the message because the Toast command has to be displayed in the Agendarf class, and the Controlagenda is only triggered after I click the save button of the Agendarf screen, ie it first executes the actions of the Scheduler class and dps does the check on the Controlragenda screen

  • This if you put in Agendarf! the result is the return: result = ca.inserts(). When the User clicks, it calls the Controlagenda and validates (or saves!). If there is an error (other than ''Record inserted with successss") then vc shows Toast

  • Thank you very much guy it went all right, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.