4

I am trying to create a custom TimePickerDialog with custom intervals for hours and minutes, and managed to solve it by using the answer from this question.

The problem is that Android Studio displays the following warning:

Accessing internal APIs via reflection is not supported and may not work on all devices, or in the future. Using reflection to access hidden/private Android APIs is not safe; it will often not work on devices from other vendors, and it may suddenly stop working[...]

The issue is in line one:

Class<?> classForid = Class.forName("com.android.internal.R$id");

Field timePickerField = classForid.getField("timePicker");
TimePicker mTimePicker = findViewById(timePickerField.getInt(null));
Field minuteField = classForid.getField("minute");
Field hourField = classForid.getField("hour");
NumberPicker minutePicker = mTimePicker.findViewById(minuteField.getInt(null));
NumberPicker hourPicker = mTimePicker.findViewById(hourField.getInt(null));

I need some alternative way of accessing the two NumberPicker objects.

Developer
  • 736
  • 7
  • 30
  • Warnings and dubious use of reflection aside, I'm almost certain that `timePickerField.getInt(null)` is not doing what you think it is anyway. It is expecting an *instance* as an argument, and you are passing null. It will presumably throw a NPE. – Michael Oct 10 '19 at 12:22
  • The code runs just fine on my device, no exceptions are thrown. – Developer Oct 10 '19 at 12:31

1 Answers1

13

I found a solution by using Resources.getSystem().getIdentifier().

The code now looks like this:

TimePicker timePicker = findViewById(Resources.getSystem().getIdentifier(
    "timePicker", 
    "id", 
    "android"
));

NumberPicker minutePicker = timePicker.findViewById(Resources.getSystem().getIdentifier(
    "minute", 
    "id", 
    "android"
));

NumberPicker hourPicker = timePicker.findViewById(Resources.getSystem().getIdentifier(
    "hour", 
    "id", 
    "android"
));
Developer
  • 736
  • 7
  • 30