How to update a database (Sqlite DB) using the Workmanager library?

Asked

Viewed 155 times

-1

I am using the workmanager library to show a notification to the user indicating the time to take his medicine.

I am also using the Sqlitedatabase library to store medicine information such as: stock, amount administered, name of remedy, type of remedy (tablet, drops), interval of hours between administrations, etc....

I use the following code to run notifications based on the interval of hours the user informs:

static final String TASK_ID = "data_update";
int intervalo = Integer.parseInt(edt.getText().toString());

PeriodicWorkRequest work =
        new PeriodicWorkRequest.Builder(DataUpdateWorker.class,
                intervalo, TimeUnit.MINUTES)
                .build();

WorkManager.getInstance().enqueueUniquePeriodicWork(TASK_ID,
            ExistingPeriodicWorkPolicy.KEEP, work);

And to show the notification I use:

public class MyPeriodicWorker extends Worker {

private static final int NOTIFICATION_ID = (int) (Math.random() * 1000);
SQLiteOpenHelperDatbase SQLOP;

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@NonNull
@Override
public Result doWork() {

    RemoteViews remoteCollapseViews = new RemoteViews("com.exemplifique.seetview"
            ,R.layout.notification_collapsed);
    RemoteViews remoteExpandeViews = new RemoteViews("com.exemplifique.seetview"
            ,R.layout.notification_expanded);

    Intent intent = new Intent(getApplicationContext(),SplashScreen_ConfirmeAlarme.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,intent,PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);


    builder.setSmallIcon(R.drawable.ic_farm_white);
    builder.setPriority(NotificationCompat.PRIORITY_HIGH);
    builder.setAutoCancel(true);
    builder.setContentIntent(pendingIntent);

    builder.setStyle(new NotificationCompat.DecoratedCustomViewStyle());
    builder.setCustomContentView(remoteCollapseViews);
    builder.setCustomBigContentView(remoteExpandeViews);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
    notificationManager.notify(NOTIFICATION_ID, builder.build());

    MediaPlayer mediaPlayer     =    MediaPlayer.create(getApplicationContext(), R.raw.alarme);
    mediaPlayer.start();

    return Result.SUCCESS;
}

So far, my application works well. However my code is incomplete. This is because every time a notification is informed to the user, the information of the medicine that is stored in Sqlitedatabase should be updated.

Example:

-Before the notification is displayed:

TABLE

Name, Category, stock, administration, interval in hours

(Rivotril,Tablet,10,1,12 in 12 hours)

-After the notification is shown:

(Rivotril,Tablet,9,1,12 in 12 hours)

That is, when the notification is generated, the database information should be updated. Now how do I do this?

Since, to make the updates of this information it is necessary to indicate in which tabala the information is stored. The following code shows what is required to update the information. This code is part of my Sqlitedatabase class where the information relating to the medicinal product in question is stored internally:

void medicamentoUpdate(String TABLE,String medicamento,String tipo,String status,String dosagem,String estoque,
                              String uso,String dataInicial,String dataFinal,String horaInicial,String intervalo){

    SQLiteDatabase db   =   this.getWritableDatabase();

    String where  =  COLUNA_NOME_MEDICAMENTO + " = '" + medicamento + "'";

    ContentValues contentValues     =   new ContentValues();
    contentValues.put(COLUNA_TIPO_MEDICAMENTO,tipo);
    contentValues.put(COLUNA_STATUS_MEDICAMENTO,status);
    contentValues.put(COLUNA_DOSAGEM_MEDICAMENTO,dosagem);
    contentValues.put(COLUNA_ESTOQUE_MEDICAMENTO,estoque);
    contentValues.put(COLUNA_USO_MEDICAMENTO,uso);
    contentValues.put(COLUNA_DATAINICIO_MEDICAMENTO,dataInicial);
    contentValues.put(COLUNA_DATAFINAL_MEDICAMENTO,dataFinal);
    contentValues.put(COLUNA_HORAINICIAL_MEDICAMENTO,horaInicial);
    contentValues.put(COLUNA_HORAINTERVALO_MEDICAMENTO,intervalo);

    db.update(TABLE,contentValues,where,null);
    db.close();
}

*The above function parameter "String TABLE" is the name of the user in which the medicine is related. This is because, my application allows the registration of multiple users and various medications. Since the registration of a new drug, will always be related to a user.

If anyone can help me there will be a generous reward in the future, once the app is generating income. (Thank you to all concerned and I ask that this passage not be erased. This is because I always keep my word)

1 answer

0

I decided to answer my own question because this one day can help someone with the same question.

Basically what I was trying to do is have access to the database (Sqlite BD). But to do so, I needed to know the name of the table on which and the drug name to update the information.

What I found out is that I can pass parameters to my Work class through the setInputData() method. Getting like this:

// É necessário armazenar o nome da tabela e o nome do remédio (Informações essas para localizar a tabela) numa variável do tipo "Data"

    Data data = new Data.Builder();

    data.putString("TABELA", "nome da tabela");
    data.putString("REMEDIO", "nome do remédio");

    workmanager.setInputData(data.build());

 WorkManager.getInstance().enqueue(workmanager.build())

And then retrieve the information in the Work class like this:

String TABELA =  inputData.getString("TABELA");
String REMEDIO =  inputData.getString("REMEDIO");

That way, I get the information to manipulate my database and update whatever is needed there.

Browser other questions tagged

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