How do I update the list of a Realtime RecyclerView when I insert a record in SQLite

1

I have an activity with a ViewPager and within three fragments and from the third fragment I have a small form and below a recyclerview that contains the data I keep in the form above, what I try to do is that when I save a record the recyclerView it is updated in real time, but I have not managed it for weeks with this problem. I attach an image so you have an idea of what I say. link I'm using

This is the Fragment

public class TarifaFragment extends Fragment implements View.OnClickListener{

EditText edtTarifa;
TextView tvFecha;
ImageButton imgbtnFecha;
Button btnCrearTarifa;

// objeto helper para gestionar operaciones con la base de datos
DBHelper conn;

// Recycler para cargar la lista de registros almacenados en la base de datos
RecyclerView recyclerTarifas;
ArrayList<Tarifa> listaTarifas;
TarifaAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_tarifa, container, false);

    // inicializar el bojeto conexion
    conn = new DBHelper(getActivity());
    listaTarifas = new ArrayList<>();

    imgbtnFecha = (ImageButton) rootView.findViewById(R.id.imgbtnFecha);
    imgbtnFecha.setOnClickListener(this);
    tvFecha = (TextView)rootView.findViewById(R.id.tvFechaTarifa);
    edtTarifa = (EditText)rootView.findViewById(R.id.edtTarifa);
    btnCrearTarifa = (Button)rootView.findViewById(R.id.btnCrearTarifa);
    btnCrearTarifa.setOnClickListener(this);
    recyclerTarifas = (RecyclerView)rootView.findViewById(R.id.recyclerTarifa);
    // setear el layout para el recyclerView
    recyclerTarifas.setLayoutManager(new LinearLayoutManager(getActivity()));

    ConsultarListaTarfias();
    adapter = new TarifaAdapter(listaTarifas);
    recyclerTarifas.setAdapter(adapter);

    return rootView;
}

private void ConsultarListaTarfias()
{
    SQLiteDatabase db = conn.getReadableDatabase();
    Tarifa tarifa = null;

    Cursor cursor = db.rawQuery("SELECT * FROM "+Utils.NOMBRE_TABLATARIFA+" ORDER BY tarifaId DESC",null);
    while(cursor.moveToNext())
    {
        tarifa = new Tarifa();
        tarifa.setId(cursor.getInt(0));
        tarifa.setTarifa(cursor.getString(1));
        tarifa.setFecha(cursor.getString(2));

        listaTarifas.add(tarifa);
    }
}

public void InsertarTarifa()
{
    SQLiteDatabase db = conn.getWritableDatabase();
    ContentValues values = new ContentValues();

    String tarifa = edtTarifa.getText().toString();
    String fechaTarifa = tvFecha.getText().toString();

    values.put(Utils.CAMPO_CANTIDADTARIFA,tarifa);
    values.put(Utils.CAMPO_FECHATARIFA,fechaTarifa);

    if(!(tarifa.equals("")) && !(fechaTarifa.equals("")) && !(fechaTarifa.equals("Fecha")))
    {
        long resultado = db.insert(Utils.NOMBRE_TABLATARIFA,Utils.CAMPO_TARIFAID,values);

        if(resultado != 0)
        {
            Log.i("Registro Creado",""+resultado);

            final SweetAlertDialog dialogo = new SweetAlertDialog(getActivity(),SweetAlertDialog.SUCCESS_TYPE);
                    dialogo.setTitleText("EXITO!")
                    .setContentText("REGISTRO CREADO CORRECTAMENTE")
                    .setConfirmText("CONTINUAR")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            dialogo.dismiss();
                        }
                    })
                    .show();
            tvFecha.setText("Fecha");
            edtTarifa.setText("");
        }
    }

    else
    {
        final SweetAlertDialog dialogo = new SweetAlertDialog(getActivity(),SweetAlertDialog.ERROR_TYPE);
        dialogo.setTitleText("ERROR!")
                .setContentText("TODOS LOS CAMPOS SON REQUERIDOS")
                .setConfirmText("CONTINUAR")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        dialogo.dismiss();
                    }
                })
                .show();
    }
    db.close();
}

@Override
public void onClick(View v) {
    switch (v.getId())
    {
        case R.id.tvFechaTarifa:
            CrearDialogoFecha(v,getActivity(),getActivity().getFragmentManager());
            break;

        case R.id.imgbtnFecha:
            CrearDialogoFecha(v,getActivity(),getActivity().getFragmentManager());
            break;

        case R.id.btnCrearTarifa:
            InsertarTarifa();
            break;
    }
}

}

This is the Adapter code

public class TarifaAdapter extends RecyclerView.Adapter<TarifaAdapter.ViewHolderTarifa> {

ArrayList<Tarifa> listaTarifas;

public TarifaAdapter(ArrayList<Tarifa> listaTarifas)
{
    this.listaTarifas = listaTarifas;
}

@Override
public ViewHolderTarifa onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_tarifas,null,false);
    return new ViewHolderTarifa(view);
}

@Override
public void onBindViewHolder(ViewHolderTarifa holder, int position) {
    Tarifa tarifa = this.listaTarifas.get(position);
    //tarifa.getMySpecialStatus();
    holder.tvTarifa.setText("Q."+listaTarifas.get(position).getTarifa());
    holder.tvFechaTarifa.setText(listaTarifas.get(position).getFecha());
}

@Override
public int getItemCount() {
    return listaTarifas.size();
}

public void update(ArrayList<Tarifa> modelList){
    this.listaTarifas.clear();
    for (Tarifa model: modelList) {
        this.listaTarifas.add(model);
    }
    notifyDataSetChanged();
}

public void replaceItem(ArrayList<Tarifa> lista)
{
    this.listaTarifas.clear();
        if(lista != null)
        {
            this.listaTarifas.clear();
            this.listaTarifas.addAll(lista);
        }
        else
        {
            this.listaTarifas = lista;
        }
        notifyDataSetChanged();
}

public class ViewHolderTarifa extends RecyclerView.ViewHolder {
    TextView tvTarifa, tvFechaTarifa;

    public ViewHolderTarifa(View itemView) {
        super(itemView);

        tvTarifa = (TextView)itemView.findViewById(R.id.tvTarifa);
        tvFechaTarifa = (TextView)itemView.findViewById(R.id.tvFechaTarifa);
    }
}

}

    
asked by Eduardo Barrios 01.08.2017 в 18:34
source

2 answers

0

Last week I was seeing persistence issues with some SQLite libraries

GreenDao: link

Realm: link

For GreenDao

This is what I usually do .. in my activity create a list from the sqlite and set it to my Adapter in the onResume

get list

public List<UserSQL> getList() {
     return daoSession.queryBuilder(UserSQL.class).list();
}

set list in Adapter

public void load(List<UserBean> users){
     this.users = users;
     notifyDataSetChanged();
}

add a model

public void add(UserBean user){
         this.users.add(user);
         notifyDataSetChanged();
}

add a list

public void addAll(List<UserBean> users) {
         this.users.addAll(users);
         notifyDataSetChanged();
}

you just have to create a method to move from SQL model to Bean ..

@Override
public void onResume(){
    super.onResume();
    adapter.load(getList());
}
    
answered by 01.08.2017 в 19:47
-1

The problem that I see, is that you are not introducing to your ArrayList the new data, so even notifying changes to the adapter as you say to have tried these will not show. Try doing something like the following:

if(!(tarifa.equals("")) && !(fechaTarifa.equals("")) && !(fechaTarifa.equals("Fecha")))
{
    long resultado = db.insert(Utils.NOMBRE_TABLATARIFA,Utils.CAMPO_TARIFAID,values);

    if(resultado != 0)
    {
        Tarifa tarifaModelo = new Tarifa();
        tarifaModelo.setId(resultado);
        tarifaModelo.setTarifa(tarifa);
        tarifaModelo.setFecha(fechaTarifa);
        listaTarifas.add(tarifaModelo);
        adapter.notifyDataSetChanged();

        Log.i("Registro Creado",""+resultado);

        final SweetAlertDialog dialogo = new SweetAlertDialog(getActivity(),SweetAlertDialog.SUCCESS_TYPE);
                dialogo.setTitleText("EXITO!")
                .setContentText("REGISTRO CREADO CORRECTAMENTE")
                .setConfirmText("CONTINUAR")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        dialogo.dismiss();
                    }
                })
                .show();
        tvFecha.setText("Fecha");
        edtTarifa.setText("");
    }
}
    
answered by 02.08.2017 в 10:08