In my database I have a list of date and time in this format "yyyy-mm-dd hh: mm". At each date and time I want to start a corresponding notification. But instead the notification starts immediately. What is wrong?
private void setAlarmFromDatabase(){
SQLiteDatabase db = mHelper.getReadableDatabase();
String sql = "SELECT _id, riserva_3 FROM riserva";
Cursor c = db.rawQuery(sql, null);
int count = c.getCount();
long[] data_ora = new long[count];
for(int i=0; i<count; i++) {
c.moveToNext();
String id = c.getString(0);
data_ora[i] = c.getLong(1);
}
c.close();
db.close();
AlarmManager[] alarmManager=new AlarmManager[24];
for(int ii=0;ii<data_ora.length;ii++)
{
alarmManager[ii] = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(getBaseContext(), Notifica_scadenza.class);
PendingIntent displayIntent=PendingIntent.getBroadcast(getBaseContext(),ii,i,0);
alarmManager[ii].set(AlarmManager.RTC_WAKEUP,(data_ora[ii]), displayIntent);
}
this.finish();
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
} The BroadcastReceiver
public class Notifica_scadenza extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Inserisci_entrate_uscite.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.allarm_icon)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(R.string.titolo_scadenza));
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
the permission in the Manifest
<uses-permission android:name="android.permission.VIBRATE" android:required="false"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="scad.Notifica_scadenza"></receiver>
Like CommonsWare mentioned most probably the problem is with the date conversion. Before the for loop define also a date formatter which you can use to format the received date from the database.
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
Now in the for loop try this:
try {
data_ora[i] = dateFormat.parse(cursor.getString(1)).getTime();
} catch (ParseException e) {
Log.e(TAG, "Something wrong happened while parsing the date.", e);
}
You can also log out the data in order to see if the data is correct or not (right after the above line).
Log.i("YOUR_TAG", "The id is: " + id + ", and the time: " + data_ora[i]);