I have a problem I think with the context when trying to run a BroadcastReceiver, what I try is to connect to an internal sqlite database and read the data. This through an Alarm that runs repeatedly every x minutes.
The code works in MainActivity () but I put the same code in a doInBackground, inside a Receiver and it throws me context error, I already tried different ways but I have not managed to make it work.
I clarify that I am a newbie in Android and if there is something that I never fully understand, it is the context. I leave the code so you can help me.
MainActivity
int interval = 1000*60*2;
Intent intent = new Intent(getApplicationContext(), CheckReclamosReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 234324243, intent, 0);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(MainActivity.this, "Alarm set in " + 10 + " seconds", Toast.LENGTH_LONG).show();
CheckReclaimsReceiver
public class CheckReclamosReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
new MyNotificationTask(context).execute();
}
}
class MyNotificationTask extends AsyncTask<String, String, Void>
{
public MyNotificationTask(Context context) {
Log.e("Ejecutandose", "tarea");
}
@Override
protected Void doInBackground(String... strings)
{
Log.e("EJECUTANDOSE", "TAREA");
UsuariosSQLiteHelper lecturabd = new UsuariosSQLiteHelper(contexto, UsuariosSQLiteHelper.TABLE_NAME_USUARIOS, null, 1);
SQLiteDatabase db = lecturabd.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(LecturasColumnas.Columnas.COLUMN_NAME_ID, id);
values.put("username", "tello");
if (db != null) {
Long todobien = db.insert(UsuariosSQLiteHelper.TABLE_NAME_USUARIOS, null, values);
}
String selectQuery1 = "SELECT * FROM " + UsuariosSQLiteHelper.TABLE_NAME_USUARIOS;
Cursor cursor1 = db.rawQuery(selectQuery1, null);
Integer cantidad1 = cursor1.getCount();
int i = 0;
if (cantidad1 > 0) {
cursor1.moveToFirst();
while (cursor1.isAfterLast() == false) {
i++;
String usuario = cursor1.getString(cursor1.getColumnIndex("username"));
Log.e("Username: ", usuario);
cursor1.moveToNext();
}
cursor1.close();
}
db.close();
return null;
}
}
Thanks for your help
The error is thrown to me in this line
UsuariosSQLiteHelper lecturabd = new UsuariosSQLiteHelper(contexto, UsuariosSQLiteHelper.TABLE_NAME_USUARIOS, null, 1);
Error:
Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase (java.lang.String, int, android.database.sqlite.SQLiteDatabase $ CursorFactory, android.database.DatabaseErrorHandler) 'on a null object reference