Search code examples
androidtextviewbroadcastreceiveralarmmanager

changing textview from another class crashes everything


I have a alarm receiver that runs in mainActivity everyday at a specific time everyday:

    public void scheduleAlarm() 
{
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 16);
    calendar.set(Calendar.MINUTE, 25);
    Intent intentAlarm = new Intent(this, AlarmReceiver.class);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}

in the other class called alarmReceiver I try to change a textView context but it crashes...

public class AlarmReceiver extends BroadcastReceiver {
NotificationCompat.Builder mBuilder;

@Override
public void onReceive(Context context, Intent intent) {
    TextView black;

    black = (TextView) ((Activity)context).findViewById(R.id.BlackCounterDisplay);
    black.setText("toto");
}

}

can't find why...


Solution

  • If you look at your stack trace, you should see a ClassCastException, as the Context passed to onReceive() is not an Activity.